views:

239

answers:

2

I have common functionality that I need to access from all screens of my app: a right bar button item and associated action.

So as not to repeat the code I would like to set this up in a custom UIViewController and have all my view controllers inherit from it.

- (void)viewDidLoad {
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(lightsCamera)];
    self.navigationItem.rightBarButtonItem = rightBarButton;
}

- (void)lightsCamera {
    …
}

However, I have a number of UITableViewControllers however and I would like to know if it is possible for them to inherit the functionality too?

+3  A: 

It's fairly trivial to recreate you own UITableViewController from your custom UIViewController subclass.

The controller must have a UITableView property, which is also set to its view property, set the proper resizing masks, set yourself as the table's delegate and datasource, and remember to flash the scrollbar indicators in -viewDidAppear: and you've more or less got it.

More here.

jbrennan
Do you know if this is the only way to achieve what I'm looking for? If so I will ditch `UITableViewController` and make my own as you suggest.
prendio2
Overriding methods in a Category is not a very good idea, so this will probably be your best bet. Alternatively, you could just subclass `UITableViewController` and add your functionality there, and then have the rest of your custom table controllers inherit from it.
jbrennan
A: 

If you're not adding any new attributes to the view controller, you can implement the two methods in a category on UIViewController and all the subclasses will inherit it by default.

TechZen
Do you mean a category on the view or on the view controller? Can I access the `navigationItem` of a view controller from its view?
prendio2
I think he meant to say UIViewController. That's where this functionality belongs. No need to involve UIView.
jlehr
Yes, sorry UIViewController. I'll edit.
TechZen