我对于以编程方式创建视图控制器的正确方法感到好奇。当我使用静态分析器编译此代码时,我会从alloc中获得泄漏(正如您所期望的那样)。我应该留下它,因为它需要留下直到应用程序退出,或者是否有更清洁的方式?
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(@"UIApplication application:");
RectViewController *myController = [[RectViewController alloc] init];
[window addSubview:[myController view]];
[window makeKeyAndVisible];
return YES;
}
欢呼加里
答案 0 :(得分:3)
在这种情况下,将视图控制器的引用作为AppDelegate上的实例变量保留,并在AppDelegate的dealloc
方法中释放它。
@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
答案 1 :(得分:2)
在app appate中保留对视图控制器的引用(dealloc中的实例,属性,合成和释放)。
然后像这样实例化它:
- (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;
}