2016-04-24 34 views
1

我正在嘗試使用託管對象上下文將數據寫入永久存儲。插入簡單的靜態數據。保存沒有返回錯誤,但提取沒有返回任何結果。這裏是我的代碼:核心數據管理對象上下文保存不起作用

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

上面的代碼除了取出部分外一切都很好。只需要很小的改變。保存發生得很好,問題只與取。 改取下面行執行:

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

我是做,而不是executeRequest的executeFetchRequest:|

相關問題