Home > DeveloperSection > Blogs > Objective-C : Property and Synthesize Directive

Objective-C : Property and Synthesize Directive

iPhone iPhone  Ios  Objective C 
0 Comment(s)
 715  View(s)
Rate this:

Objective-C : Property and Synthesize Directive

Previously we learn how to release object reference : Objective-C : NSAutoreleasePool  class


To remove the compiler error you can just declare the instance variable yourself or request the compiler to do it for you with the @synthesize statement:

@synthesize myArray=_myArray;


 Note that if you add the @synthesize statement you need to make sure that the name of the instance variable is consistent with the name used in the accessor method. In the getter method we reference _myArray so we need to specify that name in the @synthesize statement. By default if you do not specify a name for the instance variable the @synthesize statement will use the property name (without the leading underscore).

 So the following would still generate a compiler error as it would create an instance variable named myArray and not the _myArray that we are using in the getter:

@synthesize myArray;  // equivalent to @synthesize myArray=myArray;


Customizing Accessors


Accessor methods can be customized using several property declaration attributes (e.g., (copy)). Some of the most important attributes are:


getter=getterName - Customize the name of the getter accessor method. Remember that the default is simply the name of the property.


setter=setterName - Customize the name of the setter accessor method. Remember that the default is set followed by the name of the property (e.g., setName ).

readonly - Make the property read-only, meaning only a getter will be synthesized. By default, properties are read-write. This cannot be used with the setter attribute.


nonatomic - Indicate that the accessor methods do not need to be thread safe. Properties are atomic by default, which means that Objective-C will use a lock/retain to return the complete value from a getter/setter. Note, however, that this does not guarantee data integrity across threads-merely that getters and setters will be atomic. If you're not in a threaded environment, non-atomic properties are much faster.


Dot Syntax

In addition to getter/setter methods, it's also possible to use dot notation to access declared properties. For C# developers, this should be much more familiar than Objective-C's square-bracket messaging syntax:

Person *frank = [[Person alloc] init];

frank.name = @"Frank";    // Same as [frank setName:@"Frank"];

NSLog(@"%@", frank.name); // Same as [frank name];

Note this is just a convenience-it translates directly to the getter/setter methods described previously. Dot notation cannot be used for instance methods.

Don't want to miss updates? Please click the below button!

Follow MindStick