Yadnesh
Yadnesh

Reputation: 1327

Objective C memory management in between two methods

i m little confused on memory management in following scenario

-(NSData *)getData{ 
    NSData *TempData = [[NSData alloc]init];
    return TempData; 
  }

 //in some other method
 NSData *NewData = [self getData];

now the question is till when NewData will be retained and how should i release it?

Upvotes: 1

Views: 79

Answers (4)

Gaurav Goyal
Gaurav Goyal

Reputation: 167

This is wrong usage of this getter method. It should return an autoreleased copy of NSData. The autoreleased copy may or maynot be retained by the caller. Incase it is retained, its the caller's responsibility to release it.

Secondly a typo in return of this method, it should be NSData*. My typo in return. Thanks to Peter Sarnowski for pointing.

-(NSData *)getData { 
    NSData *tempData = [NSData data];
    return tempData; 
}

The caller can retain it by using the following code:

NSData *myData = [[self getData] retain];
//Some code

[myData release];

In case caller is not interested in retaining this object, he will just call

NSData *myData = [self getData];

and use within the same function from where it is called.

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

Just call release when you're done with the object:

-(NSData *)newData{ 
    NSData *TempData = [[NSData alloc]init];
    return TempData; 
}

//in some other method
NSData *NewData = [self newData];

// use data

[NewData release];

EDIT: In order to conform to the convention, the method that returns the retained object should start with new. Thanks to @PeterSarnowski.

Upvotes: 1

Oscar Gomez
Oscar Gomez

Reputation: 18488

It will stay alive till you call [newData release], your method returns a object with a retain cout of 1 because of the alloc, this means according to the cocoa memory managament rules that your method should start with new or alloc or contain copy, so change the method name to newData.

Upvotes: 1

Sabbath
Sabbath

Reputation: 91

Change your code from

-(NSData)getData{ 
    NSData *TempData = [[NSData alloc]init];
    return NSData; 
 }

to

-(NSData)getData{ 
    NSData *TempData = [[NSData alloc]init];
    return [TempData autorelease]; 
 }

or release it just by code

[NewDate release];

and I think the problem is in your getter method. It is not returning the TempData you retained.

Upvotes: 2

Related Questions