Question

I was reviewing some code and came across something that looked like this (assume it is defined for the TestObject class)

-(id) init
{
    if (self == [super init])
    {
        self.testString = @"Hello";
    }
    return self;
}

I promptly changed

if (self == [super init])

to

if (self = [super init])

But then realised that (although I know it wasn't right) the code was working as it was, I isolated the original code, in an ultra simple program

    TestObject* testObject = [[TestObject alloc] init];
    NSLog(@"%@", testObject.testString);

To my astonishment, this works. Why does the equality check instead of the assignment not break things? Why is

self == [super init]

true at the start of init, before I've even assigned it?

Était-ce utile?

La solution

self is already assigned for you. The purpose of assigning it to [super init] is to allow the superclass's -init implementation to return a different object. I highly recommend The How and Why of Cocoa Initializers (Mike Ash) and self = [stupid init]; (Wil Shipley) for more detailed discussion about why this is (or isn't) a good idea. You will find varying opinions on whether checking equality (==) is necessary.

As an aside, if you try to assign to self in any other method, you see this error message:

Autres conseils

The self pointer is established by alloc. The idiom

if(self = [super init])
{
...
}

is to protect against cases where the superclass' init needs to change the value. For example, some inits may signal failure by returning nil.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top