#import <Foundation/Foundation.h> @interface ControllerManager : NSObject { NSMutableDictionary *controllers; } + (ControllerManager *)controllerManager; - (UIViewController *)controllerByName:(NSString *)name; @end #import <Foundation/Foundation.h> @interface ControllerManager : NSObject { NSMutableDictionary *controllers; } + (ControllerManager *)controllerManager; - (UIViewController *)controllerByName:(NSString *)name; @end @implementation ControllerManager + (ControllerManager *)controllerManager { static ControllerManager *sharedInstance; @synchronized(self) { if (!sharedInstance) { sharedInstance = [ControllerManager alloc]; } } return sharedInstance; } - (UIViewController *)controllerByName:(NSString *)name { if (controllers == nil) { controllers = [[NSMutableDictionary alloc] initWithCapacity:5]; } UIViewController *ret = [controllers objectForKey:name]; if (ret == nil) { Class cls = NSClassFromString(name); ret = [cls alloc]; [ret initWithNibName:name bundle:nil]; [controllers setObject:ret forKey:name]; } return ret; } @end
If you’d like to push another view controller, do something like this;
[[self navigationController] pushViewController:[[ControllerManager controllerManager controllerByName:@"MyViewController"] animated:YES];
The first time the view loads, it is initialized from the nib. The nib must be named the same as the view controller, which by the examples I’ve seen is fairly common anyway. The view is then stored in the ControllerManager and served up as a singleton. Since you can write your view to load data before it is viewed, this pattern works well and saves memory by not allowing multiple copies of the views/controllers.