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.

猜你喜欢

转载自zl4393753.iteye.com/blog/1722659