【问题标题】:Checking for nil before releasing an object在释放对象之前检查 nil
【发布时间】:2010-10-18 11:50:48
【问题描述】:

这是好的还是坏的做法?

if (!theConnection && !receivedData) {
        // release the connection, and the data object
        [theConnection release];
        // receivedData is declared as a method instance elsewhere
        [receivedData release];
    }

【问题讨论】:

    标签: iphone objective-c cocoa-touch memory


    【解决方案1】:

    向 nil 对象发送任何消息都无效,因此您可以安全地删除该检查。

    此外,如果只有 1 个对象不是 nil,您的代码会泄漏内存。

    【讨论】:

      【解决方案2】:

      这是一种不好的做法 - 只需查看 Apple 的示例代码以了解它应该是什么样子。

      使用[theConnection release];

      [theConnection release]; theConnection = nil;

      receivedData 也是如此。

      【讨论】:

      • 这适用于每个局部变量或属性。使用(保留)属性,您可以只使用 self.theConnection = nil;虽然我不提倡从 dealloc 中这样做。
      猜你喜欢
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-08-05
      • 2011-11-16
      • 1970-01-01
      相关资源
      最近更新 更多