When a method returns an object that is taken from and NSMutableArray does开发者_如何转开发 the object must be autoreleased? Check the following method. Also should I autorelease the nil value?
-(NSObject*)getElementByID:(NSString*)ID{
for(int i=0;i<[elements count];i++){
NSObject *element = (NSObject*) [elements objectAtIndex:i];
if([element.key isEqualToString:ID]){
return [element autorelease];
}
}
return nil;
}
You must not autorelease element
because you are not an owner of it (you have not put a retain on it). You would have become an owner of it if you acquired it using alloc
, new
or retain
. Since you acquired this object calling objectAtIndex:
, you do not own it. See Three Magic Words. Calling autorelease
here will cause a crash later do to over-release.
Your method name is incorrect and breaks KVC. A method that begins with get
must take a pointer that will be updated with the result. This should be elementForID:
. As noted above with the three magic words, naming in ObjC is very important to writing stable code
As a side note, it is traditional to use id
is most cases rather than NSObject*
. They mean slightly different things, but typically id
is correct.
You never need to do any memory management related things to nil
. So, no, you should not send autorelease
to nil
.
You also should not need to send autorelease
to the element
object that you are returning from your elements
array. That object you are returning will remain in memory by virtue of elements
itself having retained it. If the calling method would like to retain
the value that you return, it may. But if that calling method only uses the returned value within its own scope, it is safe for it to do so without retaining it.
精彩评论