Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax for Objective-C init method

Tags:

Why doesn't this common property initialization scheme risk failure when the synthesized setter tries to release the undefined myArray object? Or are property objects automatically initialized to nil and I don't need to be doing this at all?

@interface myClass : NSObject {     NSArray* myArray; } @property (nonatomic, retain) NSArray* myArray; @end  @implementation myClass @synthesize myArray; -(id)init {     if ( self = [super init] ) {         self.myArray = nil;     }     return self; }  ... 
like image 416
eclux Avatar asked Nov 12 '10 14:11

eclux


2 Answers

Object instance variables in Objective-C are initialized to nil by default. Furthermore, messaging nil is allowed (unlike calling a method on null in function-calling languages like Java, C# or C++). The result of a message to nil is nil, this calling [nil release]; is just nil, not an exception.

On a side note, it's best practice to assign/call instance variables directly in -init and -dealloc methods:

-(id)init {     if ( self = [super init] ) {         myArray = nil;     }     return self; }  - (void)dealloc {     [myArray release];     [super dealloc]; } 
like image 67
Barry Wark Avatar answered Mar 01 '23 14:03

Barry Wark


As others have stated, the instance variable is already initialised to nil.

Additionally, as per Apple's documentation, instance variables should be set directly in an init method, as the getter/setter methods of a class (or subclass thereof) may rely on a fully initialised instance.

like image 22
paulbailey Avatar answered Mar 01 '23 15:03

paulbailey