I think I might be going crazy. In the following method, the return value _persistentStoreCoordinator is nil unless I add another line of code. Checking _persistentStoreCoordinator == nil is enough to make sure that it isn’t. (An NSLog statement will also do the trick.)
If I don’t add another line, _persistentStoreCoordinator is nil in the last line of the method, even though when inspecting it with break-points psc is always non-nil.
The strangest (or perhaps most helpful?) thing is that I didn’t make any changes to this class when the problems started.
Any help or explanations greatly appreciated!
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator == nil) {
NSLog(@"SQLITE STORE PATH: %@", [self pathToLocalStore]);
NSURL *storeURL = [NSURL fileURLWithPath:[self pathToLocalStore]];
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *e = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:options
error:&e]) {
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:e forKey:NSUnderlyingErrorKey];
NSString *reason = @"Could not create persistent store.";
NSException *exc = [NSException exceptionWithName:NSInternalInconsistencyException
reason:reason
userInfo:userInfo];
@throw exc;
}
_persistentStoreCoordinator = psc;
if (_persistentStoreCoordinator == nil)
{
NSLog(@"We never reach here.");
}
}
return _persistentStoreCoordinator;
}
Upon rechecking my .h file I saw that I was maintaining a weak reference to _persistantStoreCoordinator.
Sure enough, changing the reference to strong fixed things.