返回NSArray时崩溃

rob*_*rob 1 iphone cocoa-touch objective-c

我正在崩溃,因为我的阵列被解除分配,但我不知道为什么或在哪里.该数组来自于这样的东西:

@implementation Sources

- (NSArray *)sourceArray{
   NSMutableArray *array = [NSMutableArray array];
   //fill array with objects
   return (NSArray*)array;
}

@end
Run Code Online (Sandbox Code Playgroud)

然后,在tableview中,我有一个属性,我在其中覆盖getter,如下所示:

- (NSArray *)feedSourceList 
{
    if (!_sources) {    
       _feedSourceList = [_sourceList sourceArray];
    }
    return _sources;
}
Run Code Online (Sandbox Code Playgroud)

然后我像这样调用属性,这会导致崩溃:

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
    return [self.feedSourceList count];
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么数组被释放.这是自动释放池在某个我不知道的地方被耗尽了吗?保留这个阵列的正确方法是什么?

Jac*_*kin 6

你的getter应该是这样的:

- (NSArray *)feedSourceList 
{
    if (!_sources) {    
       _sources = [[_sourceList sourceArray] retain];
    }
    return _sources;
}
Run Code Online (Sandbox Code Playgroud)

返回NSArray-sourceArray自动释放的,因此在NSAutoreleasePool排水时会被释放.您需要通过调用获取返回对象的所有权-retain.

  • 请注意,这种模式确实具有脆弱性.也就是说,您正在更改getter中的状态,因此,观察者可能看不到更改,或者可能会在执行阶段看到更改,这些更改无法处理在getter获取时发生更改的事实.通常,这种延迟初始化的方式通常是最好避免的. (3认同)