2014-11-21 72 views
0

我编写了一个名为Album的应用程序(使用no-arc)作为iPhone的本机“照片”。 我的问题: 1. enter image description here (请看附加文件名:1)点击“+”按钮,然后输入一些字符串并点击“保存”按钮,应用程序将崩溃。但如果更改来自“NSMutableArray * albumArr = [[[[NSMutableArray alloc] init] autorelease];”到“NSMutableArray * albumArr = [[NSMutableArray alloc] init]”,该应用程序可以正常工作。但我认为我应该使用autorelease来发布。使用autorelease发布,应用程序将崩溃

相关的代码: // 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; 
} 
  • enter image description here (请看附加的文件名:2)分析所述代码时,我发现了潜在的物体泄漏。但在dealloc中,我已经释放。为什么会发生?
  • 相关的代码: //MainViewController.h

    @property (nonatomic, retain) AlbumModel *editingAlbum; 
    

    // MainViewController.m

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

    回答

    0

    我想你应该了解MRC。
    在第一种情况下,albumArr如果是autorelease,则意味着runloop结束时它将被释放,因此当您使用_albumArr时它将为零,您必须保留它,当将值设置为_albumArr时。
    在第二种情况下,self.editingAlbum = [[AlbumModel alloc] init];它会降低编辑相册保留cout == 2。您必须将代码更改为这样:
    AlbumModel *temp = [[AlbumModel alloc] init]; self.editingAlbum = temp; [temp release];

    +0

    在第二种情况下,我可以用另一种方式解决吗?如:使用“self”的阶段。 editingAlbum = [[[[AlbumModel alloc] init] autorelease]“来解决? – Liming 2014-11-21 08:21:49

    +0

    它也可以工作。但autorelease通常使用的返回值不能处理dealloc情况。 – 2014-11-21 08:48:03

    +0

    “因此,当您使用”no不会不会“时,_albumArr将为零 – newacct 2014-11-21 21:05:59

    相关问题