iOS:核心数据:简单示例中的NSRangeException

时间:2012-02-16 10:13:25

标签: ios core-data

我做了一个简单的核心数据示例:

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:@", "]);

MyQueuedJob.h的代码(由Xcode生成):

@interface MyQueuedJob : NSManagedObject

@property (nonatomic, retain) NSString * fooBar;

@end

此示例在模拟器中运行完美。但是当我在真正的iPhone 4上运行它时,它崩溃了以下消息:

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'

在这一行:

NSArray *fetchResults = [objectContext executeFetchRequest:request error:nil];

我做错了什么?

1 个答案:

答案 0 :(得分:1)

NSFetchRequest *request = [NSFetchRequest alloc];

你需要初始化它。将其更改为[[NSFetchRequest alloc] init];