iphone development memory leak
I have the function below which returns the allocated memory
- (NSString *) getBlock
{
NSString *block = [[NSString alloc] int];
....... doing something over here
return block;
}
// I have the class interface like this
@interface myDataDetail : NSObject {
NSString *myName;
NSString *myMarks;
}
dealloc {
myName release;
myMarks release;
开发者_C百科 [super dealloc];
}
I am doing the following stuff
myDataDetail *detail = [[myDataDetail alloc] init];
detail.myName = [self getBlock]; //here leak
detail.myMarks = [self getBlock]; //here leaak
....doing some stuff here
[detail release];
When I run the application with the Instruments Memory leak, I get leaks reported on line. What am I doing wrong here? Can some one please let me know the correct way to implement this structure.
For one, getBlock should autorelease:
- (NSString *) getBlock
{
NSString *block = [[[NSString alloc] int]autorelease];
....... doing soemthing over here
return block;
}
Because it is a getter, it should not retain. Though it shouldn't release, because that would make sure that the reference returned is invalid.
The properties accompanying your two fields should be defined to be either copy or retain. In your case, since they are NSStrings, it is best to set them to copy:
@property(nonatomic,copy) NSString *myName;
@property(nonatomic,copy) NSString *myMarks;
In your getBlock function you should autorelease the object before returning:
- (NSString *) getBlock
{
NSString *block = [[NSString alloc] int];
....... doing soemthing over here
[block autorelease];
return block;
}
This gives up the "ownership" by this function but doesn't destroy it immediately so that the function accessing it can claim "ownership"
A basic rule of memory management is that whenever you call "alloc" you should have the same function / object call "release" or "autorelease" on it at some point before the pointer to the object is destroyed. So since this is in a single function and you aren't storing the pointer in the class, you need to release it right there.
- (NSString *) getBlock
{
NSString *block =[ [[NSString alloc] int]autorelease];
return block;
}
精彩评论