Klaus
Klaus

Reputation: 35

How to load/save core data model programmatically?

I try to load and save my data model, currently just for test cases, but this might be of interest later too.

I can create a core data model, I can create objects, etc. I even found a way to save (is this the right way???) and I make the program to load it. But then the registeredObject count is 0. Does anybody understand?

//not part of the snippet here is the setup of some objects, etc. 
//mdoc is the NSPersistentDocument instance (to be precise KKDocument instance which 
//extends NSPersistentDocument)

XCTAssertTrue([[mdoc.managedObjectContext registeredObjects] count] == 5);

//save the document, note that kkFileType is the UTI-string for my model which is conform to public.xml
NSError * error;
NSURL *modelURL = [NSURL fileURLWithPath:@"testData.vith" isDirectory:FALSE];
NSLog(@"save url %@",modelURL.absoluteString);
[mdoc saveToURL:modelURL ofType:kkFileType forSaveOperation:NSSaveOperation completionHandler:^(NSError *errorOrNil){
      NSLog(@"error saving %@",errorOrNil);
}];

//load data into second document
KKDocument *second = [[KKDocument alloc] init];
XCTAssertTrue([second readFromURL:modelURL ofType:kkFileType  error:&error],@"error: %@",error);

//check that structure is provided
XCTAssertTrue(second.managedObjectContext != nil,"managedObjectContext missing");
XCTAssertTrue([second.managedObjectContext registeredObjects] != nil,"no registered Objects?");

//this test fails with message "instead 0"
XCTAssertTrue([[second.managedObjectContext registeredObjects] count] == 5, "instead %d", [[second.managedObjectContext registeredObjects] count]);

The test case is nicely executed, only the last test fails with a count of 0. The XML-file generated in between looks good too.

  1. Do I need to fetch the objects first? Or what else went wrong?
  2. And do I even use the right approach to save and load the core data model into and from and XML file? Do I need to deal with an NSPersistentStoreCoordinator instead?

Many thanks in advance!

Upvotes: 0

Views: 141

Answers (1)

ipmcc
ipmcc

Reputation: 29946

registeredObjects is going to report the number of objects that the context is "aware" of which is something different from "the number of objects in a store." If you want a count of all objects in a store, you're going to need to query that store. (i.e. perform a fetch, etc.)

In general, yes, you're going to need to use an NSPersistentStoreCoordinator if you want to persist objects (which is to say load or save them), regardless of the store type. Even in-memory stores require an NSPersistentStoreCoordinator.

In your particular case, I would expect NSPersistentDocument to be handling the NSPersistentStoreCoordinator for you though. I think your main issue here is a misunderstanding of the meaning of registeredObjects.

Upvotes: 1

Related Questions