Search code examples
objective-cinitializationoverridingallocivar

Overriding init method to allocate memory for instance variable object


I am attempting to override the init method of a class so that initializing the object also initializes the ivar object:

-(id)init 
  {
    if (self = [super init])
    {
       someIVarObject = [SomeClass alloc] init];
    }
    return self;
  }

1) Would this code even work, and even so, is this solution discouraged?
2) Why is the if condition not == ? Is it an assignment? If so, why the if?

Sorry if this is obvious! >_<


Solution

  • Yes, it would work, and afaik it's still the way it should be done.

    What it does is to call [super init] and allows it to do one of three things;

    • Return self (ie the same object self is already set to.
    • Return an entirely new object.
    • Return nil for failure.

    The result is then assigned to self, which makes sure that the rest of the constructor operates on the correct object in case it changed. The if is there to catch the case where [super init] returned nil, in which case the rest of the constructor should be skipped.