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
elementbecause 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 usingalloc,neworretain. Since you acquired this object callingobjectAtIndex:, you do not own it. See Three Magic Words. Callingautoreleasehere will cause a crash later do to over-release.Your method name is incorrect and breaks KVC. A method that begins with
getmust take a pointer that will be updated with the result. This should beelementForID:. As noted above with the three magic words, naming in ObjC is very important to writing stable codeAs a side note, it is traditional to use
idis most cases rather thanNSObject*. They mean slightly different things, but typicallyidis correct.