views:

116

answers:

3

Hi

I'm trying to use core data to write a series of persistent data (NSManagedObjects) to sqlite and then read that series in to an application. I have managed to write and read a single record during a single session, but everytime I reload the app the previous data is not loaded (and sqlite manager recognizes tables but does not recognize any entries in the tables).

here is some of the core data logic:

in applicationDidFinishLaunching: i set managedObjectContext property of 3 controllers

inputControl.managedObjectContext = context; 
reportControl.managedObjectContext = context; 
logControl.managedObjectContext = context;  

then in inputControl I add Event NSManagedObjects, such as

[event setDateCreated:[NSDate date]]; 

and in logControl I read the event logs

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 


NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; 
 [request setEntity:entity]; 

 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"dateCreated" ascending:YES]; 
 NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; 
 [request setSortDescriptors:sortDescriptors]; 
 [sortDescriptors release]; 
 [sortDescriptor release]; 

 NSError *error; 
 NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; 
 if (mutableFetchResults == nil) { 
  NSLog(@"Error fetching from DB");
 } 
 int i;
 NSLog(@"size of DB: %d",mutableFetchResults.count);
 for (i=0; i<mutableFetchResults.count; i++)
  NSLog(@"event %d: %@",i,[mutableFetchResults objectAtIndex:i]);

 [mutableFetchResults release]; 
 [request release]; 

When I run this code I see "size of DB:" as always set to '1'. managedObjectModel, managedObjectContext and persistentStoreCoordinator, are being handled in standard way.

Any assistance would be much appreciated

thank you

Peyman

+3  A: 

Are you saving your managedObjectContext?

NSError *error = nil;
if (![context save:&error]) {
    // Handle the error
}

You can fetch objects you've placed into your context, but unless you save the context to the persistant store, they won't be available next time.

kubi
This is a good answer but you should **NEVER** pass nil to the save. Always pass in an error and check your error. Even in examples :)
Marcus S. Zarra
Peyman
A: 

Where are your calls to save? Is it possible you're not flushing to the NSPersistentStoreCoordinator?

iPhoneDollaraire
Peyman
A: 

I found the problem. The context was not saving (and I was not handling the error) because a mandatory property was not being set before saving (error 1520).

thank you all for your help

Peyman

Peyman
Then kubi was correct.
Marcus S. Zarra