When my application first runs I’m using some simple code to read in some data from a source and then saving it to core data to be read back in the future. Here is my applicationDidFinishLaunching method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
categories = [[NSMutableArray alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults objectForKey:@"dataImported"]) {
NSMutableArray *temp_Categories = [[NSMutableArray alloc] initWithObjects:@"Food & Drink", @"Medical", @"Hotel", @"Travel", nil];
for(int i = 0; i < [temp_Categories count]; i++){
//Insert a new object of type ProductInfo into Core Data
NSManagedObject *categoryInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Category"
inManagedObjectContext:self.managedObjectContext];
//Set category entities values
[categoryInfo setValue:[temp_Categories objectAtIndex:i] forKey:@"categoryName"];
[categories addObject:[temp_Categories objectAtIndex:i]];
}
[defaults setObject:@"OK" forKey:@"dataImported"];
[defaults synchronize];
NSLog(@"Imported");
}
else {
//read from core data
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Category" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSMutableArray *temp_Categories = [[NSMutableArray alloc] initWithArray:[self.managedObjectContext executeFetchRequest:fetchRequest error:&error]];
for (int i = 0; i < [temp_Categories count]; i++){
NSString *category = [[temp_Categories objectAtIndex:i] objectForKey:@"categoryName"];
[categories addObject:category];
NSLog(@"Success");
}
NSLog(@"Read From Core");
}
return YES;
}
When I run this code the very first time, it works correctly, however when I run it in future (when it read from core data) it does not work, it doesn’t read in the array from core data and temp_Categories count = 0. Can anyone explain what I’m doing wrong? I’m having the same trouble trying to do the same thing with a plist file in another app.
Thanks,
Jack
EDIT 1 I’m using iOS 5.
EDIT 2 Data model screenshot:
I managed to get it to work with this:
Thanks for all your help.