核心数据管理对象上下文保存不起作用

时间:2016-04-24 12:21:01

标签: objective-c core-data

我正在尝试使用托管对象上下文将数据写入持久存储。插入简单的静态数据。 save返回没有错误但是fetch没有返回任何结果。这是我的代码:

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"MyDB" withExtension:@"momd"];`

NSManagedObjectModel *mom = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

NSAssert(mom!=nil, @"Error in initializing Managed Object Model");

NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[moc setPersistentStoreCoordinator:psc];
[self setManagedObjectContext:moc];

NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsURL = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *storeURL = [documentsURL URLByAppendingPathComponent:@"MyDB.sqllite"];

NSError *error  = nil;
NSPersistentStoreCoordinator *pscStore = [moc persistentStoreCoordinator];
NSPersistentStore *store = [pscStore addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];
NSAssert(store!=nil,@"Error in initializing PSC:%@\n%@",[error localizedDescription],[error userInfo]);

//insert
Schedule *schedule = [NSEntityDescription insertNewObjectForEntityForName:@"Schedule" inManagedObjectContext:moc];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *sessionEndDateReturned = [NSDate alloc];
sessionEndDateReturned = [dateFormatter dateFromString:@"24-04-2016"];
NSDate *sessionStartDateReturned = [NSDate alloc] ;
sessionStartDateReturned = [dateFormatter dateFromString:@"25-04-2016"];

//schedule.category = @"cat";
schedule.about = @"testabout";
schedule.endDate = sessionEndDateReturned;
schedule.eventId = @"e1";
schedule.sessionID = @"s1";
schedule.roomNumber = @"r1";
schedule.startDate = sessionStartDateReturned;
schedule.topic = @"topic1";
schedule.type = @YES;
NSLog(@"inserted objs:%@",moc.insertedObjects);
//save
NSError *insertError  = nil;
if(![moc save:&insertError]){
    NSLog(@"%@ %@",insertError,insertError.localizedDescription);
}

//fetch
NSFetchRequest *fetchReq = [NSFetchRequest fetchRequestWithEntityName:@"Schedule"];
NSError *fetchError = nil;
NSArray *result =[moc executeRequest:fetchReq error:&fetchError];
if(fetchError){
    NSLog(@"fetch Error: %@",fetchError.localizedDescription);
}
else
{
    NSLog(@"myFetch Result:%@",result);
}

任何人都可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:1)

上述代码中的一切都很好,除了取部分。只需要很小的改动。保存很好,只有fetch才有问题。 用以下行改变获取执行:

NSArray *result =[moc executeFetchRequest:fetchReq error:&error];

我正在执行executeRequest而不是executeFetchRequest:|