23

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;
}

...

3 Answers 3

29

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];
}
Sign up to request clarification or add additional context in comments.

Comments

13

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.

3 Comments

"as the getter/setter methods of a class (or subclass thereof) may rely on a fully initialised instance" do you have the source of this? Thanks!
I certainly do, it's in the Apple docs. I'll edit my answer to include a reference.
"Swift answer"? Isn't this Objective-C?
3

It's already initialized to nil.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.