[英]Adding CoreData into an existing project using Objective-C
我正在尝试使用CoreData为我的应用程序创建数据存储。 据我所知,Xcode 8 CoreData正在使用persistentContainer
而不是managedObjectContext
。
我已经使用所需的实体创建了数据模型,并从“编辑器”菜单中创建了NSManagedObject
子类。
我的问题是,当我想使用persistentContainer
,找不到标识符。
#import "UserCredentials+CoreDataClass.h"
//Fetch all username to array
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"UserCredentials"];
NSError *requestError = nil;
//I couldn't find the persistent container even though I had imported my header file.
NSArray *usernames = [self.persistentContainer.viewContext executeFetchRequest:fetchRequest error:&requestError];
我意识到我的CoreDataClass甚至根本没有属性persistentContainer
。 在哪里可以声明此位置,以便可以访问数据存储?
我假设您在创建对象时选择了核心数据选项。 您的对象上下文为null,因为它存储在AppDelegate中。 因此,您需要从appdelegate获得上下文引用,如下所示。
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSArray *usernames = [context executeFetchRequest:fetchRequest error:&requestError];
您应该创建属性
//.h文件
@property (readonly, strong) NSPersistentContainer *persistentContainer;
//.m文件
@synthesize persistentContainer = _persistentContainer;
- (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:@"CoreDataModel"]; //e.g. CoreDataModel.xcdatamodeld
[_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.
*/
RLog(@"Unresolved error %@, %@", error, error.userInfo);
abort();
}
}];
}
}
return _persistentContainer;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.