【问题标题】:What should the retainCount be when returning an object in Objective-C?在 Objective-C 中返回对象时,retainCount 应该是什么?
【发布时间】:2010-03-13 23:44:07
【问题描述】:

见标题。更具体地说,我试图返回一个对象的 mutableCopy,但是它返回的 retainCount 为 1,我担心它会泄漏。

【问题讨论】:

  • 保留计数应该是它应该是什么;具体数字并不有趣。 Dave DeLong 的回答是正确的。

标签: iphone objective-c memory-management memory-leaks


【解决方案1】:

您的方法应该遵循标准的内存管理程序。如果您的方法返回一个对象,但不包含“alloc”、“new”、“copy”、“create”或“retain”等词,则该对象应自动释放。

如果它确实包含其中一个词,那么它应该返回 +1 保留计数。

例如:

//return an autoreleased object, since there's no copy, create, retain, alloc, or new
- (id) doSomethingWithFoo:(id)foo {
  id fooCopy = [foo copy];
  [fooCopy doTheNeedful];
  return [fooCopy autorelease];
}

//return a +1 object, since there's a copy in the name
- (id) copySomethingWithFoo:(id)foo {
  id fooCopy = [foo copy];
  [fooCopy doTheNeedful];
  return fooCopy;
}

【讨论】:

    【解决方案2】:

    mutableCopy 总是增加对象的retainCount。所以,如果你使用retain、copy或mutableCopy,你必须在dealloc方法中释放。

    如果您要返回该对象,则必须使用自动释放,如下所示:

    [[[NSString alloc] initWithString:@"Test"] autorelease];
    

    自动释放池会为你释放对象,不需要在dealloc方法中释放。

    希望对你有所帮助。

    【讨论】:

    • 我明白这一点,但如果我要退回所述对象怎么办?
    • 对不起,错过了您问题中的返回部分。
    猜你喜欢
    • 2010-11-15
    • 2018-09-21
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 2010-09-17
    相关资源
    最近更新 更多