【发布时间】:2017-05-23 05:45:26
【问题描述】:
iOS 开发新手。我正在尝试在示例应用程序中使用核心数据堆栈,该应用程序通过网络获取数据并简单地更新 UI。在创建项目时,勾选了“使用核心数据”复选框,这会生成一堆样板代码。但是,在XCode 8.2.1 上,我只看到AppDelegate.m 文件中的NSPersistentContainer 实现。
- (NSPersistentContainer *)persistentContainer {
// The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
@synchronized (self) {
if (_persistentContainer == nil) {
_persistentContainer = [[NSPersistentContainer alloc] initWithName:@"ergast_coredata_objc"];
[_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
if (error != nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
NSManagedObjectContext 没有样板代码,因为大多数教程会让您相信。
因此,ViewController.m 类中的以下块失败,由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[AppDelegate managedObjectContext]: unrecognized selector sent to instance
-(NSArray *)getSeasonsList{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"SeasonData"];
NSError *error = nil;
NSArray *results = [[self getManagedObjectContext] executeFetchRequest:request error:&error];
if (!results) {
NSLog(@"Error fetching objects: %@\n%@", [error localizedDescription], [error userInfo]);
abort();
}
return results;
}
- (NSManagedObjectContext *)getManagedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
context = [delegate managedObjectContext];
return context;
}
尝试在网上查找,但大多数教程似乎都是基于 Swift 的。我在这里想念什么?开发人员是否应该为NSManagedObjectContext 提供实现?如果有人可以提供基于 Objective-c 的示例代码,将不胜感激。
谢谢!
【问题讨论】:
-
我认为您在差异视图控制器中从 appDelegate 访问 managedObjectContext,即使您没有在 appDelegate 接口中公开 getManagedObjectContext
标签: objective-c xcode core-data nsmanagedobjectcontext