Posted by Michael Dales on 2010-05-16 16:53:31
I'm a big fan of the Cocoa frameworks in general, which typically have a very clean interface. However, in Cocoa Touch there's one glaring failing with interfaces that be default cause an annoying amount of class specific knowledge leaking out into other classes, and that's the default constructors for UIViewController and UITableViewController.
By default, when you create a new UIViewController or UITableViewController in XCode it will have a constructor that requires you either provide the name of the nib file to use or the table style to use. Now the code that creates the new view controller needs to know how it's going to look - surely that detail should be taken care of inside the view controller class itself? So much for abstraction!
My solution to this, and one that I've seen others use, is to create my own default construction that simply hides these details. So for a UIViewController I definite init as such:
- (id)init
{
return [super initWithNibName: NSStringFromClass([self class])
bundle: nil]) != nil);
}
You can specify some other name for the Nib, but the typical case in XCode is that your xib file will have the same name as your class. For a UITableViewController it's even simpler:
- (id)init
{
return [super initWithStyle: UITableViewStylePlain];
}
Now, no matter what type of UIViewController subclass I'm creating, I can simply just do something like:
MyViewController *controller = [[MyViewController alloc] init];
And thus you've removed a painful dependancy between your classes. Not rocket science, but this little tip should really be something XCode does for you.