i have function with return type as (NSArray/NSData/NSString/NSDictionary and so on). i can return and use as well ,but my problem arise @ release the object. Please guide me which one is best way to manage memory for returned object.if anything is wrong please ignore and give your best solution
i have refereed apple Memory management guide
A)
-(NSData *)somefunction2
{
NSData *data=[[[NSData alloc]init]autorelease];
// fill stuff for nsdata
return data;
}
-(void)somefunction
{
NSData *data=[self somefunction2];
// use data
}
but most of the blogs advice to avoid autorelease so i was using following type
B)
-(NSData *)somefunction2
{
NSData *data=[[NSData alloc]init];
// fill stuff for nsdata
return data;
}
-(void)somefunction
{
NSData *data=[[self somefunction2] retain];
// use data
[data release];
}
C)
-(NSData *)somefunction2
{
NSData *data=[[[NSData alloc]init]autorelease];
// fill stuff for nsdata
return data;
}
-(void)somefunction
{
NSData *data=[[self somefunction2] retain];
// use data
[data release];
}
Edit:
One more thing. if i try to pass Same allocted object to Some function call Argument or custom Delegate object ,Where i have to Release ????Whether below the function call or get retain in function def and then release.
NSData *data=[[NSData alloc]init];
[self somfunctioncall:data];
or
NSData *data=[[NSData alloc]init];
[delegate mydelegatefunction:data];
-(void)somfunctioncall:(NSdata *)data
{
NSData *newdata =[data retain];
//data use
[data release];}
Thanks in advance
The best practice is that if the method contains either
alloc, init, new or retain, the method returns aretainedobject, and if it doesn’t it is returning anautoreleasedobject. I would suggest this:So that later you can just do this: