Why do I keep seeing double property declarations? [duplicate] - objective-c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When do I need to have both iVar and a property?
I keep seeing the following in objective-C code.
#interface Contact : RKObject {
NSNumber* _identifier;
NSString* _name;
NSString* _company;
}
#property (nonatomic, retain) NSNumber* identifier;
#property (nonatomic, retain) NSString* name;
#property (nonatomic, retain) NSString* company;
Why is the bit inside of the block with the interface also required? Is that instead of using #synthesize?

The block inside the #interface are the ivars for your class, while the 3 elements below it are the properties, that is accessors (getters and setters) for your ivars.
You typically access an object’s properties (in the sense of its
attributes and relationships) through a pair of accessor
(getter/setter) methods. By using accessor methods, you adhere to the
principle of encapsulation. You can exercise tight
control of the behavior of the getter/setter pair and the underlying
state management while clients of the API remain insulated from the
implementation changes.
Although using accessor methods therefore has significant advantages,
writing accessor methods is a tedious process. Moreover, aspects of
the property that may be important to consumers of the API are left
obscured—such as whether the accessor methods are thread-safe or
whether new values are copied when set.
Declared properties address these issues by providing the following
features:
The property declaration provides a clear, explicit specification of how the accessor methods behave.
The compiler can synthesize accessor methods for you, according to the specification you provide in the declaration.
Properties are represented syntactically as identifiers and are scoped, so the compiler can detect use of undeclared properties.
Reference : https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1

Extending Dr. kameleon's answer, the iVars are unnecessary in this case, as they can be declared explicitly at the #synthesize line. For instance, #synthesize name = _name would be the same as declaring the iVar in the .h (note that the property is required for this syntax). Neither one is more OK than the other, one is just more efficient coding.

Related

Type-casting #property for concrete child class [duplicate]

This question already has answers here:
Overriding #property declarations in Objective-C
(2 answers)
Closed 9 years ago.
I am designing a abstract base class for a model, where one property of the base class is currently id. I'd like the concrete classes to define what this "content" property type is. Is it safe to redefine the property with a specific type for compiler checking?
Base class .h:
#interface Foo : NSObject
...
#property (nonatomic, strong) id content;
#end
Concrete class .h:
#interface TextFoo : Foo
...
#property (nonatomic, strong) NSString *content;
#end
Concrete class .m now requires a #synthesize for NSString *content. Is this override safe to do, or are there unintended side effects? At some top level controller I will be using introspection for a collection of Foos, so I'm really only looking for compiler checking on concrete classes.
Edit: Just to add some additional information, this does actually work (Xcode 5.0.2) with no warnings or errors from the compiler. The abstract base class can even assign an arbitrary object in a setter and the subclass setter/getter still works.
To be very honest some (or I should say many) programmers would consider this a poor architecture design. You can do this but should not be doing this.
As far as the "safety" is considered, that is solely your responsibility now with this approach as compiler won't back you up here (thanks to dynamic nature of Objective-C). Your code may become completely safe if you keep in mind that content is no more an id type.
There might arise a situation where you assign content of base class to let's say NSDictionary object (which is pretty much valid) and somehow (if you are drunk and coding) you end up assigning this value to child's content (again thanks to dynamic nature of Objective-C, its pretty much valid). So now in this case you are not safe and your app might crash somewhere. So the moral of the story is I am not saying No to Drunken Coding, but I am saying no to poor architecture.

How to choose the attributes of a #property in a nutshell? [duplicate]

This question already has answers here:
Objective-C declared #property attributes (nonatomic, copy, strong, weak)
(4 answers)
Closed 9 years ago.
How to quickly know which attribute to add to a #property ?
I got it for #property (strong) and #property (weak), I think : strong if the class "owns" the referred-to instance ; weak if it is just a reference to an object whose existence is not managed to our current class.
If the property is created by dragging-and-dropping from Interface Builder, sometimes there is the cryptic unretain_unsafe or so. It sounds so complicated to me, but I believe Xcode knows what it does...
I also kind of understand that retain, assign are kind of deprecated...
And that it is better (compulsory) to use copy for NSString attributes...
But what if I want to have a #property to an int or an enum ?
Shall I choose the weak attribute if my #property points to a singleton ?
You see : so many questions for theses attributes !
I thought it would be nice to have a short and clear explanation of these attributes as some members here do :)
A few notes in no particular order
weak has the additional features of being nil-ed out when the referred-to object is deallocated, so you are never left with a dangling pointer to garbage
It is not compulsory to use copy semantics with an NSString property, but it is highly recommended. While NSString is immutable, your property might be set to a mutable string subclass, so if you don't want it changing out from under you, you should use copy
The rule of thumb for scalar property types is pretty simple: they are not reference counted, so neither strong nor weak applies. But they can be readonly or readwrite, depending on what you need.

Objective-C: Understanding Properties

So here's what I know about properties in Objective-C. Please correct me if these are not facts.
When declaring a property you are declaring the setter/getter for a instance variable
If you want to have the setter and getters defined you need to synthesize them
If you synthesize, the instance variable is defined for you. Best practice is to rename the iVar so that the getter and iVar aren't the same name. So you usually do:
#synthesize myVar = _myVar
All of my knowledge about properties is coupled with instance variables. I've watched some videos recently that say properties can be used for other instance methods besides setters/getters.
Is this true? If so, how and why would you use a property in this way? For instance I was watching a Stanford cs193p video about protocols and it said that you could have a prototype in a protocol. I could of misunderstood.
Anyways thanks to those who respond
When declaring a property you are declaring the setter/getter for a instance variable
No, you are declaring a getter and possibly a setter of a property. Period. Declaring a property does not itself imply an instance variable. There are many ways to implement a property. Instance variables happen to be a common and popular way, but non-ivar properties are very common.
If you want to have the setter and getters defined you need to synthesize them
No. (As sergio points out, I originally confused "defined" and "declared.") Almost. The #property line itself declares the setter and getter. If you want to have the setter and getter implemented for you, that is called "synthesize," but you no longer need to do this manually. The complier will automatically create a getter and setter for any property that you declare but do not implement (unless you explicitly ask it not to using #dynamic).
If you synthesize, the instance variable is defined for you. Best practice is to rename the iVar so that the getter and iVar aren't the same name. So you usually do: #synthesize myVar = _myVar
Almost. This was true a few months ago, but you no longer need to actually do that #synthesize. It will be done automatically for you by the compiler now.
This header:
#interface MyObject : NSObject
#property (nonatomic, readwrite, strong) NSString *something;
#end
is almost the same as this header:
#interface MyObject : NSObject
- (NSString *)something;
- (void)setSomething:(NSString *)something;
#end
There are some very small differences between these two, some related to the runtime and some related to the compiler, but it is clearer if you just pretend they're identical.
All you're doing in both of these cases is declaring some methods. You are not declaring how they're implemented. You're not declaring ivars. You're just declaring methods. You are now free to implement those methods any way you like. If you like, you can implement them by letting the compiler synthesize some default implementations for you. If you like you can implement them by hand. You can do one of each if you like.
Properties are synthesized by default since Xcode 4.4. So you only need to declare the property (myVar).
There will also be a _myVar available that you may use instead of accessing self.myVar.
Using a properties as a parameterless methods is torsion them into a something they are not.

How should private and public members be implemented in objective-c?

I had some discussion related to the use of properties and instance variables at work, therefore I would like to find a wiki answer for that. Now, I know there's no real private member type in objective-c, everything is pretty much public. However, I'm a little bit concerned about the way we should design our classes and also to comply to OOP principles. I would like to hear opinions of these three design approaches:
A. According to various post and even to a new Stanford university iPhone development courses, you should always use properties everywhere you can. However IMHO, this approach brakes OOP design principles because in this case, all members become public. Why do I need to publish all my internal/local instance variables to outside? Also, there's some very little (but still) overhead if you use synthesized setters via properties, instead using local ivar directly. Here's a sample:
//==== header file =====//
#interface MyClass : NSObject
#property (nonatomic, retain) NSString *publicMemberWithProperty;
#property (nonatomic, retain) NSString *propertyForPrivateMember;
#end
B. Another approach is to declare ivars in header file (without declaring relative properties) for private members, and in the same header file, to declare pure properties (without declaring relative ivars) for public members. In such case, ivars would be used directly in the class. This approach makes sense but not uses all benefits from properties because we have manually to release old values before setting the new ones. Here's a sample:
//==== header file =====//
#interface MyClass : NSObject{
NSString *_privateMember;
}
#property (nonatomic, retain) NSString *publicMemberWithProperty;
#end
C. To declare pure properties (without declaring relative ivars) for public members in header file, and to declare pure properties (without declaring relative ivars) for private members in private interface in implementation file. This approach IMHO is more clear than the first one, but the same question remains: why do we have to have properties for internal/local members? Here's a sample:
//==== header file =====//
#interface MyClass : NSObject
#property (nonatomic, retain) NSString *publicMemberWithProperty;
#end
//==== implementation file =====//
#interface MyClass()
#property (nonatomic, retain) NSString *propertyForPrivateMember;
#end
This decision freedom annoys me a little bit and I would like to find a confirmation from respective sources about how things should be done. However, I was unable to find such strict statements in Apple docs on that, so please post a link to apple docs if any exists, or to any other theory that clears that.
By using class extensions you can have private properties.
A class extension syntax is simple:
Inside the .m-file, that has the class, create a unnamed category:
.h
#interface OverlayViewController : UIViewController <VSClickWheelViewDelegate>
- (IBAction)moreButtonClicked:(id)sender;
- (IBAction)cancelButtonClicked:(id)sender;
#end
.m
#import "OverlayViewController.h"
#interface OverlayViewController ()
#property(nonatomic) NSInteger amount;
#property(retain,nonatomic)NSArray *colors;
#end
#implementation OverlayViewController
#synthesize amount = amount_;
#synthesize colors = colors_;
//…
#end
Now you got all the aspects of properties for private members, without exposing them to public. There should be no overhead to synthesized properties to written getter/setters, as the compiler will create more or less the same at compile time.
Note that this code uses synthesized ivars. No ivar declaration in the header is needed.
There is a nice cocoawithlove article, about this approach.
You also ask why to use properties for private ivars. There are several good reasons:
properties take care for ownership and memory management.
at any point in future you can decide, to write a custom getter/setter. i.e. to reload a tableview, once a NSArray ivar was newly set. If you used properties consequently, no other changes are needed.
Key Value Coding support properties.
public readonly properties can be re-declared to private readwrite properties.
Since LLVM 3 it is also possible, to declare ivars in class extensions
#interface OverlayViewController (){
NSInteger amount;
NSArray *colors;
}
#end
or even at the implementation block
#implementation OverlayViewController{
NSInteger amount;
NSArray *colors;
}
//…
#end
see "WWDC2011: Session 322 - Objective-C Advancements in Depth" (~03:00)
There really is not a clean, safe, zero overhead, solution to this which is directly supported by the language. Many people are content with the current visibility features, while many feel they are lacking.
The runtime could (but does not) make this distinction with ivars and methods. First class support would be best, IMO. Until then, we have some abstraction idioms:
Option A
Is bad - everything's visible. I don't agree that it is a good approach, and that is not OOD (IMO). If everything is visible, then your class should either:
support all cases for how the client may use your class (usually unreasonable or undesirable)
or you provide them with a ton of rules via documentation (doc updates are likely to go unnoticed)
or the accessors should have no side effects (not OOD, and frequently translates to 'do not override accessors')
Option B
Has the deficiencies of Option A,, and like Option A, members may be accessed by key.
Option C
This is slightly safer. Like all the others, you can still use keyed access, and subclasses may override your accessors (even if unknowingly).
Option D
One approach to this is to write your class as a wrapper over over an implementation type. You can use an ObjC type or a C++ type for this. You may favor C++ where speed is important (it was mentioned in the OP).
A simple approach to this would take one of the forms:
// inner ObjC type
#class MONObjectImp;
#interface MONObject : NSObject
{
#private
MONObjectImp * imp;
}
#end
// Inner C++ type - Variant A
class MONObjectImp { ... };
#interface MONObject : NSObject
{
#private
MONObjectImp imp;
}
#end
// Inner C++ type - Variant B
class MONObjectImp;
#interface MONObject : NSObject
{
#private
MON::t_auto_pointer<MONObjectImp> imp;
}
#end
(Note: Since this was originally written, the ability to declare ivars in the #implementation block has been introduced. You should declare your C++ types there if it isn't necessary to support older toolchains or the 'fragile' 32-bit OS X ABI).
C++ Variant A is not as 'safe' as the others, because it requires the class' declaration visible to the client. In the other cases, you can declare and define the Imp class in the implementation file -- hiding it from clients.
Then you can expose the interface you choose. Of course, clients can still access your members if they really want to via the runtime. This would be easiest for them to do safely with the ObjC Imp type -- the objc runtime does not support C++ semantics for members, so clients would be asking for UB (IOW it's all POD to the runtime).
The runtime cost for the ObjC implementation is to write a new type, to create a new Imp instance for each instance, and a good amount of doubling of messaging.
The C++ type will cost practically nothing, apart from the allocation (Variant B).
Option E
Other approaches often dissociate ivars from interfaces. While this is a good thing, it's also very unusual for ObjC types. ObjC types/designs often maintain close relations to their ivars and accessors -- so you'll face resistance from some other devs.
Similarly to C++, Objective C provides public, private, and protected scopes. It also provides a package scope which is similar to package scope as defined in Java.
Public variables of classes can be references anywhere in the program.
Private variables can only be referenced within messages of the class that declares it. It could be used within messages that belong to ANY instance of the same class.
Package scope is similar to public scope within the same image, i.e. executable or library. According to Apple’s documentation, on 64-bit architectures, variables of package scope defined within a different image are to be treated as private.
Variable scope is defined by #public, #private, #protected, #package modifiers. These modifiers can be used both in a way similar to C++ or Java. All variables listed under a scope declaration belong to the same scope. Also, variables can be listed on the same line where the scope is declared.
#interface VariableScope : NSObject {
#public
int iVar0;
#protected
int iVar1;
#private
int iVar2;
#package
int iVar3;
#public int iVar01, iVar02;
#protected int iVar11, iVar12;
#private int iVar21, iVar22;
#package int iVar31, iVar32;
}
#end
For more info use the below link
http://cocoacast.com/?q=node/100

Properties and Instance Variables in Objective-C

I'm rather confused about properties and instance variables in Objective-C.
I'm about half-way through Aaron Hillegass's "Cocoa Programming for Mac OS X" and everything is logical. You would declare a class something like this:
#class Something;
#interface MyClass : NSObject {
NSString *name;
NSArray *items;
Something *something;
IBOutlet NSTextField *myTextField;
}
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSArray *items;
Since other objects need to manipulate our name and items instance variables, we use #property/#synthesize to generate accessors/mutators for them. Within our class, we don't use the accessors/mutators—we just interact with the instance variable directly.
something is just an instance variable that we're going to use in our class, and since no one else needs to use it, we don't create a pair of accessors and mutators for it.
We need to interact with a text field in our UI, so we declare an IBOutlet for it, connect it, and we're done.
All very logical.
However, in the iPhone world, things seem to be different. People declare properties for every single instance variable, declare properties for IBOutlets, and use accessors/mutators to interact with instance variables within the class (e.g. they would write [self setName:#"Test"] rather than name = #"Test").
Why? What is going on? Are these differences iPhone-specific? What are the advantages of declaring properties for all instance variables, declaring properties for IBOutlets, and using accessors/mutators within your own class?
In the iPhone world, there's no garbage collector available. You'll have to carefully manage memory with reference counting. With that in mind, consider the difference between:
name = #"Test";
and
self.name = #"Test";
// which is equivalent to:
[self setName: #"Test"];
If you directly set the instance variable, without prior consideration, you'll lose the reference to the previous value and you can't adjust its retain count (you should have released it manually). If you access it through a property, it'll be handled automatically for you, along with incrementing the retain count of the newly assigned object.
The fundamental concept is not iPhone specific but it becomes crucial in an environment without the garbage collector.
Properties are used to generate accessors for instance variables, there's no magic happening.
You can implement the same accessors by hand.
You can find in Aaron Hillegass's book examples of 3 memory management strategies for member variables. They are assign/copy/retain. You select one of those as required for given variable.
I assume you understand memory management in Objective-c ...
Accessors hide the complexity and differences of memory management for each variable.
For example:
name = #"Test"
is a simple assignment, name now holds reference to NSString #"Test". However you could decide to use copy or retain. No matter which version of memory management you chose accessor hides the complexity and you always access the variable with (or similar):
[self setName:#"Test"]
[self name]
Now setName: might use assign/copy or retain and you don't have to worry about it.
My guess is that iPhone tutorials use properties to make it easier for new developers to jump through memory management (even though it's handy to generate appropriate accessors with properties rather than implement them by hand every time).
However, in the iPhone world, things seem to be different. People declare properties for every single instance variable, declare properties for IBOutlets, and use accessors/mutators to interact with instance variables within the class (e.g. they would write [self setName:#"Test"] rather than name = #"Test").
That's not iPhone-specific. Except in init methods and the dealloc method, it's good practice to always use your accessors. The main benefit, especially on the Mac (with Cocoa Bindings), is that using your accessors means free KVO notifications.
The reason why people “declare properties for every single instance variable” is most probably that all of their instance variables are things they want to expose as properties. If they had something they would want to keep private, they would not declare a property for it in the header file. (However, they may make a property for it in a class extension in the implementation file, in order to get the aforementioned free KVO notifications.)
Declaring properties for outlets is overkill, in my opinion. I don't see a point to it. If you don't make a property, the nib loader will set the outlet by direct instance-variable access, which is just fine for that task.
I would suggest that modern development has made a very strong attempt to identify, define and apply best practices.
Among these best practices we find continuity and consistency.
Apart from arguing over use of accessors in init and dealloc methods, accessors should generally be used all the time (inside and outside of a class) for the benefits they offer, including encapsulation, polymorphic var implementations (which both allow for abstracting and refactoring) and to facilitate those best practices of continuity and consistency. The fundamental benefits of an object-orient language come into play when doing things in this way and exploiting the fullness of the language's capabilities. Always being consistent in one's coding is an oft undermentioned benefit, as any senior programmer will usually attest.
You can write like this
//MyClass.h
#class Something;
#interface MyClass : NSObject
#property (nonatomic, strong) NSString *name;
#property (nonatomic, strong) NSArray *items;
#end
//MyClass.m
#interface MyClass()
#property (nonatomic, strong) IBOutlet NSTextField *myTextField;
#property (nonatomic, strong) Something *something;
#end