Reputation: 5698
I have been fixing a bug and wound up in some pretty old code, and I've found something I don't fully understand
We have are currently initializing an object like this:
MyViewController* myViewController = [MyViewController viewControllerForDocument:(MyDocument*)doc];
and +viewControllerForDocument
is a class method:
+ (instancetype)viewControllerForDocument:(MyDocument*)myDocument
{
MyViewController* result = nil;
result = [[MyViewController alloc] initWithNibName:@"MyViewController"
bundle:[NSBundle mainBundle]];
if ( result )
{
[result view];
[result.myController setDocument:myDocument];
[myDocument setController:result.myController];
}
return result;
}
I know it looks pretty funny, but my question is why would a developer choose to instantiate an object through a class method-- instead of just writing a custom instance initializer? The implementation of the class method contains the instance initializer -initWithNibName
anyways.
The reason why this is an issue now, is because [result view]
loads the nib which calls -awakeFromNib
.
-awakeFromNib
needs to be aware of myDocument
; but because the initializer is a class method I can't store myDocument
into a instance property.
I also can't move [result.myController setDocument:myDocument];
before the [result view]
call because myController is loaded through the nib.
Anyways this whole thing just stinks to me, and the fact that it was written in 2010 by an employee that is long gone makes me skeptical.
Can anybody shed some light on possible motivation to implement things this way? I also don't think that manually loading objects through the nib by accessing the view
is good either, but I don't really have any reason to say it's bad
Upvotes: 1
Views: 51
Reputation: 112855
How is this particularly different than the following from the NSString
class method:
+ (instancetype)stringWithUTF8String:(const char *)bytes
Both are class methods, sometimes called convenience initializers.
They were more useful prior to ARC where they avoided the alloc
init
autorelease
pattern:
MyClass *inst = [[[MyClass aloc] init] autorelease];
Upvotes: 2