I’m trying to implement a category on my MainContainerViewController that returns the main instance:
In my .h:
@interface UIViewController(MainViewExtension)
/** Convience method for getting access to the MainContainerViewController instance */
- (MainContainerViewController *)mainContainerExtension;
@end
In my .m
@implementation UIViewController(MainViewExtension)
- (MainContainerViewController *)mainContainerExtension
{
return (MainContainerViewController *)self;
}
@end
And so from some outside view controller, I do self.mainContainerExtension to access the instance, and there is only one instance declared, but it’s not giving me the right instance.
NSLog(@"number of children:%i", [self.mainContainerExtension.childViewControllers count]);
This returns 0 even though it should be 3, so that’s how I know it’s not giving me the right results. Am I missing something?
Edit: The way I know it’s not giving me the correct instance is because in the viewDidLoad of the MainContainerViewController, I have this:
- (void)viewDidLoad
{
appDelegate.notesViewController=[[NotesViewController alloc] init];
appDelegate.notesViewController.mainContainer=self;
[self addChildViewController: appDelegate.notesViewController];
}
Each NotesViewController has a property of type MainContainerViewController, so that I always have a way to access the MainContainerViewController from NotesViewControllers. But I just learned about categories and extensions, and I thought it might be easier to just implement a category that gives me access to the container view from whichever view I’m in, rather than having a property on every view controller. It’s my first time, so I’m sure I’m doing something wrong with my category implementation, just not sure what it is.
I don’t think instance method returning self can be useful. Whatever object you would invoke that on: [someVC mainContainerExtension], you would already have the answer: it’s someVC.
If each NotesViewController has a property for the containing VC, then aren’t you all set? As long as it’s public in the NotesVC header:
Also note, unless there’s only one NotesViewController in the app, the one getting assigned in appDelegate will be overwritten. The handle in the appDelegate will be the last one allocated.