使用Objective-C将CoreData添加到现有项目中

时间:2017-02-15 07:57:28

标签: ios objective-c core-data

我正在尝试使用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。我在哪里可以声明这个,所以我可以访问我的数据存储?

2 个答案:

答案 0 :(得分:1)

我假设您在创建对象时选择了核心数据选项。您的对象上下文为null,因为它存储在AppDelegate中。所以你需要从appdelegate获取上下文参考,如下所示。

NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSArray *usernames = [context executeFetchRequest:fetchRequest error:&requestError];

答案 1 :(得分:1)

你应该创建属性

//。h file

@property (readonly, strong) NSPersistentContainer *persistentContainer;

//。m file

@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;
}