我有一个从 AppDelegate 开始的核心数据数据库,我会这样做:
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
如果 YES
从 复制它>Appdelegate
。
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@", managedObjectContext);
}
只需尝试删除这两行并在我建议的条件下添加上面的内容。应该可以。
Update 1: As you are asking I am mentioning steps for creating Appdelegate's instance to access global properties.
#import "AppDelegate.h"
在@implementation
之后创建Appdelegate
的实例
AppDelegate *app;
在 viewDidLoad
方法中...
app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
关于ios - 访问其他类的核心数据数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10062208/