Reputation: 2495
If I use this custom getter:
-(NSMutableArray *)queue
{
if (_queue == nil)
{
if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
return [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
//[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
return [[NSMutableArray alloc] init];
}
}
}
_queue is always (null). I don't know why it happens.
But if I use the same code in init:
if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
sharedQueue.queue = [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
sharedQueue.queue = [[NSMutableArray alloc] init];
}
It works like magic. Why am I doing it wrong?
Upvotes: 0
Views: 129
Reputation: 25740
When you create a custom getter, you need to set the underlying ivar before returning the value.
Change:
if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
return [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
//[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
return [[NSMutableArray alloc] init];
}
To:
if ([[NSFileManager defaultManager] fileExistsAtPath:kOfflineQueueFilePath]) {
_queue = [NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
//[NSKeyedUnarchiver unarchiveObjectWithFile:kOfflineQueueFilePath];
}else{
_queue = [[NSMutableArray alloc] init];
}
return _queue;
Upvotes: 2