Releasing objects returned by method

冷暖自知 提交于 2019-11-30 22:23:03

usually you would autorelease it

-(NSThing*)myMethod{

  NSThing *thing = [[NSthing alloc] init];
  // do some stuff with the thing
  return [thing autorelease];
}

Autoreleasing is the easy way to get out of this, as newacct said. However, you should take into consideration the "ownership" of the object you're returning.

In Objective-C, the general rule of thumb is that any method with alloc, new, or copy in its name returns an object that is not autoreleased, while other methods (like class methods) pre-autorelease the object to be returned. So these three are not equivalent in terms of autorelease (although the compiler may do some magic and reduce them all to string constants anyway):

// Autoreleased
NSString *string1 = [NSString stringWithString:@"aString"];
NSString *string2 = [[[NSString alloc] initWithString:@"aString"] autorelease];

// NOT autoreleased
NSString *string3 = [[NSString alloc] initWithString:@"aString"];

Your code can take a similar approach, where you consider who owns the object you're returning. In the specific example you provided, the method is the one allocing and initing the object, so in general you're responsible for autoreleaseing [sic] it within your own method. However, if you were to write a method that takes a preexisting object and modifies it in some way, you would not own that object and would not be responsible for autoreleasing the returned object. (Doing so could actually cause problems down the road when the autorelease pool to which the object belongs gets drained.)

See also (thanks to Peter and Quinn in the comments!):

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!