如果我使用这个自定义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];
}
它就像魔法一样。为什么我做错了?
答案 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;