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; } ...
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]; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With