【问题标题】:use the autorelease to release,the app will crash使用autorelease释放,应用会崩溃
【发布时间】:2014-11-21 01:33:20
【问题描述】:

我编写了一个名为 Album 的应用程序(使用无弧),它作为 iPhone 的原生“照片”。 我的问题: 1. (请看附件名:1)当点击“+”按钮,然后输入一些字符串并点击“保存”按钮时,应用程序将崩溃。但如果将代码从“NSMutableArray *albumArr = [[ [NSMutableArray alloc] init] autorelease];"到“NSMutableArray *albumArr = [[NSMutableArray alloc] init]”,应用程序可以正常工作。但我认为我应该使用自动释放来释放。

相关代码: // 专辑数据库.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. (请看附件名: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];
}

【问题讨论】:

    标签: ios crash autorelease


    【解决方案1】:

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

    【讨论】:

    • 第二种情况,能不能用其他方法解决?比如:用“self.editingAlbum = [[[AlbumModel alloc] init] autorelease]”这个阶段来解决?跨度>
    • 它也可以工作。但是autorelease通常使用的返回值你不能处理dealloc的情况。
    • "所以当你使用时 _albumArr 将为零"不,它不会
    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多