Pregunta

I have this class (let's call it FooViewController) that's a subclass of UIViewController. It's supposed to act similarly to a UINavigationController, in that there's a rootController and you can add other UIViewControllers to it. And each UIViewController within FooViewController can create another UIViewController and push that new UIViewController to FooViewController.

Here's an example of what I mean. This is the auto-created code when you add a new UITableViewController to your project.

DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"Nib name" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];

Here's the question: How can I have a variable like navigationController in all of my UIViewControllers? Just like you can add methods to existing classes using categories, can you also add variables to existing classes? It sounds like Associative References is what I'm looking for, but it's only available on a Mac.

One solution that would work for me is to subclass all the UIViewControllers that I might use, and have my actual classes subclass off of those. For example, I might do:

@interface FooUIViewController : UIViewController {
    FooViewController *fooViewController;
}

@interface FooUITableViewController : UITableViewController {
    FooViewController *fooViewController;
}

So that I could do: [self.fooViewController pushViewController:detailViewController];. But this seems like a dirty way of doing it.

I feel this shouldn't be a difficult thing to do and maybe I'm thinking about it wrong. Any thoughts? Thanks!

¿Fue útil?

Solución

No, you can't add an instance variable to UIViewController.

Subclassing is not a bad way of doing it, considering more things it can do in relation to FooViewController. It doesn't harm the design of your classes because they depend on FooViewController anyway (just as the same as UIViewController having navigationController property).

Another way of doing it is to access the FooViewController object via the application delegate. But I think this is a dirty way of doing it (because they now depend on your application delegate).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top