Why put [super init] inside the if statement, since the return value is zero, do we still return it?

The CS193p course says that the if statement must be in the init method to check if it works [super init]:

if (self = [super init]) {
    self.someProperty = parameter;    
}
return self;

I don’t understand why this is done, as if [super init]returning nil, does the method itself also return nil, regardless of the result of the if statement?

EDIT: Question: why put self = [super init]inside an if statement. (Not: why self = [super init]at all)

+3
source share
6 answers

This makes sense, because in some cases [super init] may return nil, and in this case, if you try to access some ivar, you will fail.

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

Apple Objective-c . ( " " )

Apple if

self = [super init];
if (self) {
    //init stuff...
}
return self;

LLVM 2.0, , . :

if ((self = [super init])) {
    //init stuff...
}
return self;
+1

if(self = [super init]){.... init , alloc 'd.

0

[super init], , . init , .

[super init] self Objective-C. , , , . , NSString

, self = [super init]

[[super alloc] init], [super init], , ,

0

if.

self = [super init];
if ( self ) {
    self.someProperty = parameter;    
}
return self;

if self, self.someProperty = parameter

0

self = [[super alloc] init]; creates a base class and the runtime suffocates when you try to call methods only for a subclass later.

self = [super init]; - normal vision in Objective-C when the base class needs to initialize the values ​​of variables or create composite elements, otherwise they are created using the values ​​Nil or (0).

-1
source

Source: https://habr.com/ru/post/1794268/


All Articles