开发者

Help with Memory leak: init NSMutableArray from file

开发者 https://www.devze.com 2023-04-01 06:03 出处:网络
In some point in my app, I need to load a list from a file, so I implement this method to load the list:

In some point in my app, I need to load a list from a file, so I implement this method to load the list:

-(void)loadList
{
    NSString *filePath = [self dataFilePath];  //This is a method return the开发者_JAVA百科 path of file
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
        self.list = [[NSMutableArray alloc]initWithArray:tempArray];
        [tempArray release];
    }
}

The self.list is a (retain) property.

I think the leak is from [alloc] when I init the selfl.list. I used

self.list = [[[NSMutableArray alloc]initWithArray:tempArray]autorelease];

But the app crashes due to EXC_BAD_ACCESS. So I am confused here how to solve this.

Thanks for any suggestions.


Just assign,

self.list = tempArray;

As tempArray is already an array, you don't have to create another array from it. You ca directly assign to self.list.


  There is no need to allocate another time for array .So just assign directly

    -(void)loadList
   {
NSString *filePath = [self dataFilePath];  //This is a method return the path of file
if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSMutableArray *tempArray = [[NSMutableArray alloc]initWithContentsOfFile:filePath];
    self.list = [tempArray copy];
    [tempArray release];
}
 }


Don't autorelease it. (I guess).


is your list property assign or retain? if it is retain, then you should change this:

self.list = [[NSMutableArray alloc]initWithArray:tempArray];

to this:

self.list = [[NSMutableArray arrayWithArray:tempArray];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号