Simple UIViewController Management

I’m writing a navigation based application for the iPhone and need to instantiate the same UIViewController (for a screen) in more than one place. In some sample code I’ve seen, local copies are kept in an NSArray. I’ve been doing that myself until I decided the Factory design pattern was probably more useful. I wrote the code below and it has been working very well.

#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.

4 thoughts on “Simple UIViewController Management

  1. Dave,

    I noticed you are quite the iOS developer, I saw some of your code in the Zxing app.

    Do you do contract work?

    If so.. pop me an email.

    We have a specific web project that needs some client device pieces written, and you seem to be well versed.

    Great blog.

    Brad-

    1. Thanks, Brad!
      I’m not really for hire anymore. I’m working for a startup now and that demands more of my time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s