I have more of a conceptual question than code based because my code works.
When my app launches I fetch the sessionObject from coreData and validate the authToken.
This code works when in my loading controller. The Fetch request works and returns an array of sessionObjects. However in App Delegate where I validate the authToken the returned array is empty. Why does the code work in a controller but not in the App Delegate? There are no errors from the fetch request. The context is not nil. It's the exact code I use in the loading controller and that works.
Do I have to do requests differently for CoreData in the App Delegate? Can I use a fetch request in App Delegate?
Sample Code in the app Delegate DidBecomeActive method. I use DidBecomeActive so we can validate on return from background and init.
// check for valid authtoken if present so the correct home screen will display
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"CurrentSession" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
CurrentSession *sessionObj = nil;
NSError *cdError = nil;
if([self managedObjectContext] == nil){
NSLog(@"context is nil");
}
NSArray *sessionArray = [[[self managedObjectContext] executeFetchRequest:request error:&cdError] mutableCopy];
if (sessionArray != nil && [sessionArray count]) {
sessionObj = (CurrentSession *)[sessionArray lastObject];
NSLog(@"Found session %@",sessionObj.authToken);
if (![sessionObj.authToken isEqualToString:@""]) {
[Solid_Utilities validateAuthToken:[self managedObjectContext]];
}
} else {
NSLog(@"NO SESSION FOUND");
}
EDIT I'm sure my issue may be thread related. In the loading controller I run a lot of tasks on separate threads and I assume App Delegate runs on main thread. However the context I provide to the loading controller is generated in app delegate.
EDIT I did a isMainThread check in App Delegate and Loading controller and both came back as true. Not sure why if they use the same context and store they wouldn't return the same array of objects.