Question

With ARC, every pointer assignment does a retain by default. In that light, in noatomic cases, why do I even need to declare properties?

How are these two any different?

//Property
@interface I1 : NSObject 
@property (nonatomic, strong) NSString* str;
@end

I1 *obj1 = ...;
obj1.str = [[NSString alloc] init...];

//Only member variable
@interface I2 : NSObject { 
@public
    NSString* str;
}
@end
I2 *obj2 = ...;
obj2->str = [[NSString alloc] init...];
Was it helpful?

Solution

Memory management is not the only advantage of using properties.

Two in particular that come to mind for me is:

  1. KVO (without having to manually call willChangeValueForKey: and didChangeValueForKey: - see Manual Change Notification)
  2. Ability to write custom logic for a setter and getter as well as write subclass customizations for the setter and getter.

bbum wrote a great response to this in iOS: must every iVar really be property?

OTHER TIPS

Properties is a part of the Objective Orientation Programming. This is encapsulation! How they can not be used?! Always use properties to encapsulate your data.

@property/@synthesize pairs autogenerate getters and setters, and thus affording encapsulation.

Of course, often this encapsulation might not be needed right now, but maybe in the future you'll decide to add some lazy initialization to the iVar, or want to post a notification when the content of the iVar changes. It's good habit to always use properties and synthesized or hand-written accessors, and the cost is negligible. Why would you not use them?

(If you are concerned that @property/@synthesize is too much boilerplate, and you have a Mac Dev account, have a look at the Beta forum.)

I would think properties are still used for automatically generating accessors and mutators where @public isn't used.

In the interface use @property because that is advertising public access. If you do not want to actually make it a public put the @property declaration in a class extension or the ivar declaration in the @implementation in the .m file.

In objective-c, @property is just a abbreviation for standard setter and/or getter of a variable in the class. So no matter your ARC option is on or off, you can make your choice at your convenience.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top