use the autorelease to release,the app will crash

434 views Asked by At

I write an app (using no-arc)named Album which as the iPhone's native "Photo". My Question: 1. enter image description here (please look the attached file name:1)when clicking the button of "+",then inputing some string and clicking the button of "save",the app will crash.But if change the code from "NSMutableArray *albumArr = [[[NSMutableArray alloc] init] autorelease];" to "NSMutableArray *albumArr = [[NSMutableArray alloc] init]", the app can work fine.But I think I should use the autorelease to release.

The related code: // AlbumDB.m

+ (NSMutableArray *)fetchAlbumData
{
#warning why autorelease crash?
    NSMutableArray *albumArr = [[[NSMutableArray alloc] init] autorelease];
    FMDatabase *db = [FMDatabase databaseWithPath:[self dataBasePath]];

    if ([db open]) {
        NSString *sqlSelect = @"SELECT * FROM ALBUM";
        FMResultSet *result = [db executeQuery:sqlSelect];
        while ([result next]) {
            AlbumModel *albumModel = [[AlbumModel alloc] init];
            albumModel.albumid = [result intForColumn:@"albumid"];
            albumModel.albumName = [result stringForColumn:@"albumName"];
            [albumArr addObject:albumModel];
            [albumModel release];
        }

        [db close];
    }
    return albumArr;
}
  1. enter image description here (please look the attached file name:2)when analyzing the code,I find the potential leak of an object.But in the dealloc,I had released.Why happen?

The related code: //MainViewController.h

@property (nonatomic, retain) AlbumModel *editingAlbum;

// MainViewController.m

- (void)dealloc
{
    [_albumArr release], _albumArr = nil;
    self.editingAlbum = nil;
    self.detailViewController = nil;
    [super dealloc];
}
1

There are 1 answers

3
Feng Lin On BEST ANSWER

I think you should learn more about mrc.
In your first case, the albumArr if it is autorelease , it means when the runloop end ,it will be release, so the _albumArr will be nil when you use, you must retain it ,when you set the value to _albumArr.
In the second case, self.editingAlbum = [[AlbumModel alloc] init]; It will casuse the editingAlbum retain cout ==2 .You must change the code to like this:
AlbumModel *temp = [[AlbumModel alloc] init]; self.editingAlbum = temp; [temp release];