I’ve seen a way of initialising a view controller that intrigued me. Could be my lack of experience, but I find it very useful, however, I’m trying to see if there are any reasons for which one should avoid it so I know if I should adopt it as well.
UIViewController* imageC = [UIViewController imageViewController];
Where imageViewController is a static method in a category:
+(UIViewController*) imageViewController
{
return [[UIViewController alloc] initWithNibName:@"ImageViewController" bundle:nil];
}
Is this good, reliable design? I think so, but not sure. Being a static method means it lacks context, but not sure that’s a problem in this case. What are the problems you can run in on long term if you use this approach?(If any)
There are a couple of issues with your code. First, there are no static methods in Objective C. There are class methods, and they, same as instance methods, do dynamic dispatch. They just use the class object for this.
And that leads us to the second issue: Your code always allocates an instance of
UIViewController, even when called on a subclass. That’s not expected behavior for Objective-C.[NSMutableArray array]returns a mutable array, even thougharrayis a convenience constructor defined inNSArray.The third issue is minor: It would be beneficial for users of subclasses if you would declare your method to return
instancetype. That way your saying the method returns an instance of the receiver class and the compiler can do its static type checking. The concept is calledrelated return typeand was only recently introduced with clang.Here’s a better version: