I import the registered user data from the server into the main data object called "User". I also keep a reference to this specific User object to my AppDelegate (as a property), so I can access it elsewhere in my application. The problem I am facing is that when I click on another view controller and try to access appdelegate.loggedInUser.id, I see that "id" is zero. The debugger shows this for the object:
$24 = 0x0b28ad30 <User: 0xb28ad30> (entity: User; id: 0xb261160 <x-coredata:///User/tC48E8991-B8A6-4E68-9112-93F9F21DB5382> ; data: <fault>)
I realized that the Core Data infrastructure will fail with the moment when I try to access one of the properties of this object. I am confused, why am I accessing the user id property, does not raise an error in this case?
EDIT
Here's how to create and use a loggedInUser object:
//method to get bgContext +(NSManagedObjectContext *)getContextOnBgWithParentSetToMainMOC { NSManagedObjectContext *tmpContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; [tmpContext setParentContext:[Utils getAppDelegate].managedObjectContext]; return tmpContext; } //in App Delegate NSManagedObjectContext *bgContext = [NSManagedObjectContext getContextOnBgWithParentSetToMainMOC]; self.loggedInUser = [User importFromObject:loggedInUserData inContext:bgContext completionBlock:^(NSManagedObjectContext *theContext, NSManagedObject *theManagedObjectWithValuesImported) {}]; //In User.m file + (User *)importFromObject:(NSDictionary *)dictionary inContext:(NSManagedObjectContext *)context completionBlock:(TemporaryContextImportReturnBlock)block { if ( !context ){ context = [NSManagedObjectContext getContextOnBgWithParentSetToMainMOC]; } NSManagedObjectContext *localContext = context; User *newUserEntity = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:localContext]; NSArray *emailsArray = [dictionary objectForKey:@"emails"]; NSString *emailsString = @""; if ([emailsArray count] > 0){ emailsString = [emailsArray componentsJoinedByString:@","]; } newUserEntity.emails = emailsString; newUserEntity.id = [dictionary objectForKey:@"id"]; newUserEntity.n = [dictionary nonNullObjectForKey:@"n"]; return newUserEntity; } //Access in one of the view controllers User *loggedInUser = [Utils getAppDelegate].loggedInUser; // loggedInUser.id /*nil*/
ios objective-c core-data
Trunal bhanse
source share