Search code examples
objective-cpointersinitializationself

(Objective-C)Is it safe to redefine self within class method?


Is it safe to reinitialise self within a class method?

MyClass * a = [[MyClass alloc]init];

@implementation MyClass
{
    -(id)init
    {
        if(self = [super init])
        {
            ...
        }
        return self;
    }
    -(void)redefine
    {
         //??
         self = [self init];

    }

}

will a point to the reinitialized instance of MyClass?

Thank You, nonono


Solution

  • Provided that (a) your class and its superclasses can be re-init'ed without leaking memory or resources and (b) you know that your class and its superclasses inits all return the self they are passed and not a reference to some other object, then yes...

    Otherwise things will go wrong. Consider your redefine method; in the body of this method self is just a local variable whose contents is initialized to point to some object. Changing the value in that local variable does not change the object it originally pointed at, or the value of any other variables which point to that object. E.g. consider the variation:

    @implementation Q
    {
        - (void) redefine
        {
             self = [[Q alloc] init]; // changes the *local* self to refer to a new object
        }
        ...
    }
    
    ...
    Q *someQ = [[Q alloc] init];     // allocate an object
    [someQ redefine];                // NO effect on someQ, another Q is just created and leaked
    

    Clearly this does not alter someQ, and your version may not either. Your code will have the effect you wish if and only if you know init always returns the object it was passed - which is not guaranteed in Obj-C.