【问题标题】:iOS basic memory managementiOS 基础内存管理
【发布时间】:2011-10-19 05:03:14
【问题描述】:

我正在阅读 Big Nerd Ranch 关于 iOS 编程的书,我对他们在第 7 章中创建的 Hypnotime 程序有疑问。

在某些时候,他们实现了以下方法:

- (void)showCurrentTime:(id)sender
{
    NSDate *now = [NSDate date];

    static NSDateFormatter *formatter = nil;

    if (!formatter) {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
    }

    [timeLabel setText:[formatter stringFromDate:now]];

}

我的问题是关于NSDateFormatter *formatter。格式化程序是用allocinit 创建的。我一直都知道任何带有alloc 的东西都需要在某个地方发布,对吧?当formatter 被传递给timeLabel 时,timeLabel 不发送retain 给它吗?并且不能(不应该?)我随后发布formatter

我浏览了接下来几页上的代码,除了release 被发送到dealloc 中的timeLabel 之外,我在任何地方都找不到任何发布消息。

我是不是把事情搞混了? formatter 有什么理由不应该被我释放?我想成为一个好的记忆公民。任何帮助表示赞赏:)

【问题讨论】:

    标签: iphone ios ios4 memory-management


    【解决方案1】:

    由于 static 关键字,formatter 将保持可用直到下次调用该方法时,作为一个全局变量 - 好吧,不是 全局

    查看关于static的维基百科条目

    【讨论】:

    • 感谢您的快速回复。 wiki 条目清除了一些关于 static up 的内容:)
    【解决方案2】:

    他们将格式化程序声明为静态,因此目的是让格式化程序在应用程序的整个生命周期内保持活动状态。这将是出于性能原因,并且可能是一个未成熟的优化,因此在您自己的未来开发中不要将此作为最佳实践。

    //static (even in a method) will allow formatter to live during entire app lifecycle
    static NSDateFormatter *formatter = nil;
    
    //Check if formatter has been set (this is not thread safe)
    if (!formatter) {
        //Set it once and forget it, it wont be a leak, and it wont ever be released
        formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
    }
    

    【讨论】:

    • 感谢您的建议。如果它在应用程序的整个生命周期内都保持活动状态,这是否意味着我应该在 dealloc 中释放它或根本不释放它?老实说,对此有点困惑。
    • 不,它不打算被释放,也不会造成内存泄漏,除非再次分配格式化程序而不先释放它。这就是为什么有一个 if 检查。
    • 好的,我想我明白了。非常感谢。
    【解决方案3】:

    setText 只是获取一个字符串(不是格式化程序本身),所以格式化程序不会被保留。我敢打赌,他们在控制器的其他地方使用格式化程序,因此它会在 dealloc 中释放

    【讨论】:

    • 不要介意 dealloc 部分,没看到它是静态的,但第一部分仍然正确
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-12
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多