简体   繁体   English

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

[英]What should the retainCount be when returning an object in Objective-C?

See title. 参见标题。 To be more specific, I am trying to return the mutableCopy of an object, however it's returned with a retainCount of 1 and I am worrying that it will leak. 更具体地说,我试图返回一个对象的mutableCopy,但是它返回的keepCount为1,我担心它会泄漏。

Your method should follow standard memory management procedures. 您的方法应遵循标准的内存管理过程。 If your method returns an object, but does not contain the words "alloc", "new", "copy", "create", or "retain", then the object should be autoreleased. 如果您的方法返回一个对象,但不包含单词“ alloc”,“ new”,“ copy”,“ create”或“ retain”,则该对象应被自动释放。

If it does contain one of those words, then it should be returned with a +1 retain count. 如果它确实包含这些单词之一,则应返回+1保留计数。

For example: 例如:

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

mutableCopy always increment the retainCount of an object. mutableCopy总是增加一个对象的retainCount。 So, if you use retain, copy or mutableCopy you must release in dealloc method. 因此,如果使用保留,复制或可变复制,则必须以dealloc方法释放。

If you are returning that object you must to use autorelease, like this: 如果要返回该对象,则必须使用自动释放,如下所示:

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

The autorelease pool will release the object for you and there is no need to release in dealloc method. 自动释放池将为您释放对象,而无需使用dealloc方法释放。

Hope that helps you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM