PDA

View Full Version : how do _you_ load your managedObjectContext?


black bear theory
2007.06.27, 01:49 AM
how do you guarantee that your data is fully loaded when you open a coredata-based document?

i've been reading about it and one of the strengths of coredata appears to be the ability to load data as needed from a persistent store. my program doesn't contain a lot of data (though it does store a single, sometimes large, image) and i would like it all available at the beginning.

i found that adding some code to awakeFromNib in MyDocument did the trick:

-(void)awakeFromNib {
// !!!:20070626 don't modify this code unless you want to fix
// the 'image not loading on file open' problem
NSLog(@"documentMO : %@", [self documentMO]);
[[self documentMO] valueForKey:@"image"];
[_view setImage:[self image]];
[_view setScale:[self scale]];
// [scaleSlider setIntValue:];
// </!!!>
}

// almost direct copy from apple's department tutorial
-(NSManagedObject *)documentMO {
if (documentMO != nil) {
return documentMO;
}
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSError *fetchError = nil;
NSArray *fetchResults;

@try {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"DocumentMO"
inManagedObjectContext:moc];
[fetchRequest setEntity:entity];
fetchResults = [moc executeFetchRequest:fetchRequest error:&fetchError];
} @finally {
[fetchRequest release];
}

if ((fetchResults != nil) && ([fetchResults count] == 1) && (fetchError == nil)) {
[self setDocumentMO:[fetchResults objectAtIndex:0]];
return documentMO;
}

if (fetchError != nil) {
[self presentError:fetchError];
}
else {
// should present custom error message...
}
return nil;
}

-(NSImage *)image { return [[documentMO valueForKeyPath:@"image"] valueForKeyPath:@"image"]; }



and i was happy. my image loaded fine and all the data drawn on top of it. i made changes, closed, reopened, changed, quit, relaunched, etc. and the image would always show up.

so i decided to make some changes to another part of my program, in my custom view, completely apart from MyDocument and now the image doesn't load properly anymore. :mad:

i've read some about this and know that the reasons for not loading lots of data at once is due to speed etc. but i am interested in just having it work. consistently!