【问题标题】:How to handle retain count for controllers saved in AppDelegate?如何处理保存在 AppDelegate 中的控制器的保留计数?
【发布时间】:2011-12-03 03:11:01
【问题描述】:

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];
}

如果我执行 Product->Analyse,我会收到“潜在泄漏”和“不正确递减”警告。这样做的正确方法是什么,或者假设我的方法没问题,我该如何告诉分析工具忽略这些行?

【问题讨论】:

    标签: ios retaincount


    【解决方案1】:

    即使您的代码看起来不错,但您为什么要这样做?它可能会导致局外人阅读您的代码时感到困惑,而且您不应该显式调用属性上的释放,您应该让内存管理发生在属性本身中,因此像

    一样重写您的代码
    - (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];
    }
    

    【讨论】:

    • 我以为属性只是保留,而不是释放对象,所以混淆的不仅仅是外部读者。感谢您指出正确的方法!
    猜你喜欢
    • 2017-12-19
    • 2013-12-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多