Ios 访问其他类中的核心数据数据库
我有一个从AppDelegate开始的核心数据数据库,在那里我将执行以下操作:Ios 访问其他类中的核心数据数据库,ios,core-data,nsmanagedobjectcontext,nsfetchedresultscontroller,Ios,Core Data,Nsmanagedobjectcontext,Nsfetchedresultscontroller,我有一个从AppDelegate开始的核心数据数据库,在那里我将执行以下操作: MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease]; masterViewController.managedObjectContext = self.managedObjectConte
MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController" bundle:nil] autorelease];
masterViewController.managedObjectContext = self.managedObjectContext;
通过这种方式,我可以在主视图中访问数据库,然后我想访问其他类中的核心数据,我这样做:
id delegateContext = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegateContext managedObjectContext];
但是,当我添加和访问信息时,我在尝试访问数据库信息时,在代码的各个部分中出现了一些错误Exc访问和其他错误,因此我认为可能我以错误的方式使用了核心数据来访问其他类的信息
也许我必须释放delegatecontext?…我没有在我使用过的任何类中释放它,如果我已经释放了它,我在哪里做了它
有人能帮我吗?问题是您正在使用id类型的delegateContext而不是NSManagedObjectContext,并在这两行中将其分配给*Context
id delegateContext = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegateContext managedObjectContext];
在需要保存或访问managedObjectContext时添加这些行如何?如果为nil,请检查它是否为nil,如果为YES,请从Appdelegate复制它
只要试着删除这两行,并添加上述条件,如果我建议。应该有用
更新1:正如你所问,我提到了创建
Appdelegate的实例以访问全局属性
@implementation之后创建Appdelegate的实例
在viewDidLoad方法中
app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
谢谢你的回答,所以我必须在.h文件中声明managedObjectContext,并在dealoc方法中发布它?是的。在每个类中,无论您决定在哪里使用核心数据,都必须在.h文件中声明managedObjectContext,在.m文件中合成并释放它。好的,非常感谢!今晚我尝试了,但现在我接受了答案:随时因为我当前的核心数据项目是以这种方式工作的。我试过了,但在这里给我一个错误:AppDelegate*和错误:使用未使用的标识符'AppDelegate',我必须在my.m中导入AppDelegate.h?。。。或者我不能把AppDelegate*?更新的答案。请查收。。
#import "AppDelegate.h"
AppDelegate *app;
app=(AppDelegate *)[[UIApplication sharedApplication]delegate];