Karuppu MGR Karuppu MGR - 5 months ago 9
iOS Question

Records returned from executeFetchRequest is empty if the app is run the second time

Im facing a weird data loss while using core data.

Im using the following code to save records to core data.

for (int i = 0; i < [domains count]; i++){

NSString *is_active = [[domains objectAtIndex:i] objectForKey:@"is_active"];
NSString *domain_id = [[domains objectAtIndex:i] objectForKey:@"domain_id"];
NSString *domain_name = [[domains objectAtIndex:i] objectForKey:@"domain_name"];

[context performBlockAndWait:^{
NSManagedObject *domain = [NSEntityDescription insertNewObjectForEntityForName:@"Domains" inManagedObjectContext:context];
[domain setValue:is_active forKey:@"isActive"];
[domain setValue:domain_id forKey:@"domainId"];
[domain setValue:domain_name forKey:@"domainName"];
}];
}


Im using the following code to fetch records.

NSError *error;
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Domains"];

self.domainContext = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

NSLog(@"domain context %@",self.domainContext);


Im using the real device to do the testing.

if im running the app in my device for the first time, self.domainContext has got some contents in it. where as if im running the app the second time without closing the app manually, the self.domainContext doesnt have any contents within it. However if I close the app manually ans re run the app, self.domainContext has got the contents saved. Why is that so? The data is being persisted to the disk only if i close my app manually. If I run the app from xcode without closing my app manually, data is not being persisted.

Answer

You have not save the context.So that you lost the data on second time. Change your code like this

for (int i = 0; i < [domains count]; i++){

    NSString *is_active = [[domains objectAtIndex:i] objectForKey:@"is_active"];
    NSString *domain_id = [[domains objectAtIndex:i] objectForKey:@"domain_id"];
    NSString *domain_name = [[domains objectAtIndex:i] objectForKey:@"domain_name"];

    [context performBlockAndWait:^{
        NSManagedObject *domain = [NSEntityDescription insertNewObjectForEntityForName:@"Domains" inManagedObjectContext:context];
        [domain setValue:is_active forKey:@"isActive"];
        [domain setValue:domain_id forKey:@"domainId"];
        [domain setValue:domain_name forKey:@"domainName"];
    }];
    NSError *error = nil;
    [context save:&error];
}

Hope this will help you.

Comments