AppDelegate viewController memory leak?
I am just curious with regards to the correct way to create a view controller programatically. When I compile this code with the static analyser I get a leak (as you would expect) from the alloc. Should I just leave it as it needs to stay until the app exits anyways, or is there a cleaner way?
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"UIApplication application:");
RectViewController *myController = [[RectViewController alloc] init];
[window addSubview:[myController view]];
[window makeKeyAndVisible];
开发者_如何学JAVA return YES;
}
cheers Gary
In this case, keep a reference to your view controller as an instance variable on the AppDelegate and release it in the AppDelegate's dealloc
method.
@interface AppDelegate : NSObject {
// ...
RectViewController *myController;
}
// ...
@end
@implementation AppDelegate
// ...
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"UIApplication application:");
myController = [[RectViewController alloc] init];
[window addSubview:[myController view]];
[window makeKeyAndVisible];
return YES;
}
- (void) dealloc {
// ...
[myController release];
[super dealloc];
}
// ...
@end
Keep a reference to the view controller in you app delegate (instance, property, synthesize and release in dealloc).
And then instantiate it like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"UIApplication application:");
RectViewController *rootControllerTemp = [RectViewController new];
self.rootController = rootControllerTemp;
[rootControllerTemp release];
[window addSubview:[self.rootController view]];
[window makeKeyAndVisible];
return YES;
}
精彩评论