如何处理AppDelegate中保存的控制器的保留计数?

时间:2011-12-03 03:11:02

标签: ios retaincount

MyAppDelegate正在做一些后台工作,需要在此期间刷新几个视图,所以我保存了对每个创建的控制器的引用。

@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    SomethingController *currentSomethingController;
}
@property (nonatomic, retain) SomethingController *currentSomethingController;

这样做是为了打开控制器:

- (void)openSomethingController {
    MyAppDelegate * app = [[UIApplication sharedApplication] delegate];
    app.currentSomethingController = [[SomethingController alloc] init];
    [self presentModalViewController:app.currentSomethingController animated:NO];
}

在控制器内部调用它来关闭它:

- (void)dismissSelf
{
    MyAppDelegate * app = [[UIApplication sharedApplication] delegate];
    [app.currentSomethingController release];
    app.currentSomethingController = nil;
[self dismissModalViewControllerAnimated:NO];
}

在MyAppDelegate中,控制器正在向控制器发送消息:

- (void)longRunningBackgroundTask {
    [currentSomethingController performSelectorOnMainThread:@selector(updateData) withObject:nil waitUntilDone:YES];
}

如果我做产品 - &gt;分析我得到“潜在泄漏”和“错误减量”警告。什么是正确的方法或假设我的方法是好的,我如何告诉分析工具忽略这些线?

1 个答案:

答案 0 :(得分:0)

即使你的代码看起来很好,你为什么这样做?它可能会导致对读取代码的局外人产生混淆,也就是说你不应该在属性上显式调用release,你应该让属性本身出现内存管理,所以重写你的代码就像

- (void)openSomethingController {
    MyAppDelegate * app = [[UIApplication sharedApplication] delegate];
     SomethingController *controller=[[SomethingController alloc] init];
    app.currentSomethingController = controller;
    [controller release];
    [self presentModalViewController:app.currentSomethingController animated:NO];
}

然后

- (void)dismissSelf
{
    MyAppDelegate * app = [[UIApplication sharedApplication] delegate];
    app.currentSomethingController = nil;
   [self dismissModalViewControllerAnimated:NO];
}