Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa Objective-C init oddity

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?

like image 451
jbat100 Avatar asked Dec 21 '22 07:12

jbat100


1 Answers

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:

like image 190
jtbandes Avatar answered Jan 06 '23 22:01

jtbandes