本文介绍了使用Objective-C将CoreData添加到现有项目中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CoreData为我的应用程序创建数据存储。据我所知,Xcode 8 CoreData使用的是 persistentContainer 而不是 managedObjectContext

I'm trying to create a data storage for my application using CoreData. From what I know, Xcode 8 CoreData is using persistentContainer instead of managedObjectContext.

我已经使用所需的实体创建了数据模型,并从编辑器菜单中创建了 NSManagedObject 子类。

I've created a data model with my required entities and created an NSManagedObject subclass from the Editor menu.

我的问题是,当我想使用 persistentContainer 时,找不到标识符。

My problem is that when I want to use the persistentContainer, there is no identifier found.

#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 。我在哪里可以声明它,以便访问数据存储?

I realised that my CoreDataClass did not even have the property persistentContainer at all. Where can I declare this at, so I can access my data storage?

推荐答案

我假设您在选择核心数据选项的同时创建您的对象。您的对象上下文为null,因为它存储在AppDelegate中。因此,您需要从appdelegate获得上下文引用,如下所示。

I am assuming you have selected core data option while creating your object. Your object context is null because it is store into AppDelegate. So you need to get context reference from appdelegate like below.

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

这篇关于使用Objective-C将CoreData添加到现有项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 20:32