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! >_<
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;
self
is already set to.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.