I’m trying to understand memory management better. If I have a function that returns an autorelease NSArray like this
// DataClass
- (NSArray *)getData {
NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
// do some stuff to get data from sqlite
return array;
}
then in another class file, I want to use this getData. I have a property
@property (nonatomic, retain) NSArray *myData;
- viewDidLoad {
NSMutableArray *data = [[NSMutableArray alloc] init];
data = [DataClass getData];
self.myData = data;
[data release];
}
Why do I get a bad access error in this case? I know it’s because of [data release], but I thought that since the getData method returns an autorelease NSArray, and because I initialize a new NSMutableArray with alloc/init, then I’d need to release it? Or is what happening is even though I initialize data with alloc/init, I then am not even using it because with the data=[DataClass getData] statement, I point to a different NSArray, and then try to release that already autoreleased NSArray from getData, and then the NSMutableArray data is still floating around in memory somewhere? Thanks in advance.
Your guess is correct. 🙂
First of all, as written, in
viewDidLoadyou leak thedatayou alloc/init on line 1 when you assigndatathe result of callinggetDataon line 2.And then, you are correct, that
dataat this point is pointing at an autoreleased object. So callingreleaseon it is a bad thing.Frankly, in your
viewDidLoadmethod, you really don’t need the call togetDataat all. The complete and appropriate sequence for this kind of operation is:assuming that the data property is defined with
retain. By using theself.prefix, you get aretaindone for you.Does this help?