Why put [super init] inside of an if statement since whether or not the return is nil we return it anyway?
On the CS193p course they says that in an init开发者_JS百科 method there should be an if statement to check if the [super init]
works:
if (self = [super init]) {
self.someProperty = parameter;
}
return self;
I don't understand why this is done, as if the [super init]
returns nil, the method itself will also return nil, no matter the outcome of the if statement?
EDIT: The question is; why put self = [super init]
inside an if statement. (Not: Why have self = [super init]
at all)
That's make sense because in some cases [super init] can return nil, and in this case if you try to access some ivar you'll get crash.
Example:
-(id) init {
self = [super init];
some_ivar = [[NSObject alloc] init]; //compiler treats this as self->some_ivar
//if self == nil you'll get EXC_BAD_ACCESS
return self;
}
Apple explains this particular concept in detail in there Objective-c programming guide. (Scroll down to the section "Handling Initialization Failure")
However Apple example code often keeps the self assignment outside the if statement
self = [super init];
if (self) {
//init stuff...
}
return self;
And if you are using the LLVM 2.0 compiler, it will give you a warning and tell you to wrap your statement in parentheses, too. Like this:
if ((self = [super init])) {
//init stuff...
}
return self;
It should be if(self = [super init]){...
. init
is an instance method and thus can only be called on an object that has already been alloc
'd.
You need to call [super init] so that the superclass can do any one-time initialization that it needs to do. The init method returns a pointer representing the object that was initialized.
Assigning the result of [super init] back to self is a standard Objective-C convention. It's done in case the superclass, as part of its initialization work, returns a different object than the one originally created. NSString's, for example, do this
So it's self = [super init]
I have never seen [[super alloc] init], i've always used [super init], and as far as my knowledge, that's the convention
It doesn't have to be in an if
statement.
you can very well have it like
self = [super init];
if ( self ) {
self.someProperty = parameter;
}
return self;
the if statement is there to check that self
was initialized properly and it is safe to do self.someProperty = parameter
self = [[super alloc] init]; creates a base class and the runtime will choke when you try to invoke subclass-only methods later on.
self = [super init]; is a common sight in Objective-C when the base class needs to initialize variable values or instantiate composite members, otherwise they are created with Nil or (0) values.
精彩评论