自定义getter为null

时间:2012-11-18 17:02:27

标签: iphone objective-c ios xcode cocoa-touch

如果我使用这个自定义getter:

-(NSMutableArray *)queue
{
    if (_queue == nil)
    {
        if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
            return [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];

            //[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
        }else{
            return [[NSMutableArray alloc] init];
        }
    }
}

_queue总是(null)。我不知道为什么会这样。

但是如果我在init中使用相同的代码:

  if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {            
        sharedQueue.queue =  [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
    }else{
        sharedQueue.queue = [[NSMutableArray alloc] init];
    }

它就像魔法一样。为什么我做错了?

1 个答案:

答案 0 :(得分:2)

创建自定义getter时,需要在返回值之前设置基础ivar。

变化:

if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
    return [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];

    //[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
    return [[NSMutableArray alloc] init];
}

要:

if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
    _queue = [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];

    //[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
    _queue =  [[NSMutableArray alloc] init];
}
return _queue;