Reputation: 1145
I made a simple Core Data Example:
NSLog(@"Loading...");
NSURL *modelUrl = [[NSBundle mainBundle] URLForResource:@"CoreDataTest" withExtension:@"momd"];
NSManagedObjectModel *objectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelUrl];
NSManagedObjectContext *objectContext = [[NSManagedObjectContext alloc] init];
NSError *error = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSURL *storeUrl = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:@"DB.sqlite"]];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:objectModel];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSPersistentStore *migratedStore = [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error];
if(migratedStore == nil) {
NSLog(@"Could not initialize or migrate store: %@", [error localizedDescription]);
}
[objectContext setPersistentStoreCoordinator:coordinator];
MyQueuedJob *queuedJob = (MyQueuedJob *) [NSEntityDescription insertNewObjectForEntityForName:@"MyQueuedJob" inManagedObjectContext:objectContext];
queuedJob.fooBar = @"Test";
[objectContext save:&error];
sleep(2);
NSFetchRequest *request = [NSFetchRequest alloc];
NSEntityDescription *entDesc = [NSEntityDescription entityForName:@"MyQueuedJob" inManagedObjectContext:objectContext];
[request setEntity:entDesc];
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:@"fooBar" ascending:YES];
[request setSortDescriptors:[[NSArray alloc] initWithObjects:sortDesc, nil]];
NSLog(@"fetching jobs...");
NSArray *fetchResults = [objectContext executeFetchRequest:request error:nil];
NSLog(@"jobs fetched!");
NSLog(@"%@", [fetchResults componentsJoinedByString:@", "]);
Code of MyQueuedJob.h (generated by Xcode):
@interface MyQueuedJob : NSManagedObject
@property (nonatomic, retain) NSString * fooBar;
@end
This example runs perfectly fine in the simulator. But when I run it on my real iPhone 4, it crashes with the following message:
2012-02-16 11:06:44.819 CoreDataTest[345:707] Loading...
2012-02-16 11:06:46.937 CoreDataTest[345:707] fetching jobs...
2012-02-16 11:06:46.950 CoreDataTest[345:707] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
on this line:
NSArray *fetchResults = [objectContext executeFetchRequest:request error:nil];
What am I doing wrong?
Upvotes: 1
Views: 502
Reputation: 9093
NSFetchRequest *request = [NSFetchRequest alloc];
You need to init this. Change it to [[NSFetchRequest alloc] init];
Upvotes: 1