在Objective-C中返回对象时,retainCount应该是什么?

sky*_*erl 0 iphone memory-leaks memory-management objective-c

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

Dav*_*ong 10

您的方法应遵循标准的内存管理程序.如果您的方法返回一个对象,但不包含单词"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;
}
Run Code Online (Sandbox Code Playgroud)