코어 데이터를 사용하여 프로젝트의 데이터를 유지해야합니다. 지금까지 수행 한 작업은 잘 수행되었지만 실제로 코어 데이터를 사용하여 작업을 저장하기 시작하면 프로그램이 종료되고 이유를 모르겠다. appDelegate 파일에서 핵심 데이터에 필요한 모든 구성 요소를 설정하고 DetailViewController
이라는 viewController
에 데이터를 저장하려고합니다. 여기에 내가 무엇을했는지이다 : 나는 데이터를 저장하기 위해 상세보기에서 메소드를 호출 할 때 핵심 데이터에 대한기존 프로젝트에서 코어 데이터 사용
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Set the tab bar controller as the window's root view controller and display.
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
//this is what I added, reference managedObjectContext in the detail view controller.
detailViewController = [[DetailViewController alloc] init];
detailViewController.managedObjectContext = [self managedObjectContext];
return YES;
}
모든 구성 요소는
- (NSManagedObjectContext *) managedObjectContext {
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
- (NSManagedObjectModel *)managedObjectModel {
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory]
stringByAppendingPathComponent: @"MyProjectName.sqlite"]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[self managedObjectModel]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeUrl options:nil error:&error]) {
/*Error for store creation should be handled in here*/
}
return persistentStoreCoordinator;
}
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
을 구현 한 프로그램이 종료됩니다.
-(IBAction) addItem {
Info *info = [NSEntityDescription insertNewObjectForEntityForName:@"Info"
inManagedObjectContext:managedObjectContext];
info.name = item.name;
}
item
은 상세 뷰의 현재 개체입니다, Info
는 모델 클래스 파일입니다. 내가 여기 뭔가보고 싶니?
감사합니다.
업데이트 :
콘솔에서 오류 메시지가 : 응용 프로그램을 종료
인해 캐치되지 않는 예외 'NSInternalInconsistencyException', 이유에 '+ entityForName : 엔티티 이름에 대한 NSManagedObjectModel을 찾을 수 없습니다'정보 ''
하지만 "Resources"폴더에는 Info.xcdatamodel 파일이 있고 엔티티 이름은 "Info"입니다.
모델에 엔티티'@ "정보가 있습니까? 디버그 콘솔에 표시되는 오류는 무엇입니까? – Nekto
예, 모델 파일이 생성되었으며 엔티티 이름은 "Info"입니다. – Michael
'managedObjectContext! = nil'입니까? – Nekto