开发者

Correct syntax for Objective-C init method

开发者 https://www.devze.com 2023-01-25 07: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 automatica开发者_StackOverflow中

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 automatica开发者_StackOverflow中文版lly 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.


It's already initialized to nil.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号