【发布时间】:2010-12-10 11:41:27
【问题描述】:
我对某些以某种方式无效的 Core Data 对象有疑问。 托管对象上下文位于应用程序委托中,我在视图表中使用它从数据库中获取“注释”对象并显示它们。 我为各个部分(今天、昨天等)构建了一个数组,并为每个部分构建了一个包含该部分中的注释的数组,如下所示:
// in the .h file
NSMutableArray* data; // An array containing an array of thoughts for each section.
@property (nonatomic, retain, readonly) NSManagedObjectContext* objectContext;
// in the .m file, when loading the view
ThoughtsAppDelegate* appDelegate = (ThoughtsAppDelegate*)[[UIApplication sharedApplication] delegate];
objectContext = appDelegate.managedObjectContext;
NSEntityDescription* descriptor = [[NSEntityDescription entityForName:@"Note"
inManagedObjectContext:objectContext] autorelease];
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:descriptor];
NSError* error;
NSArray* notes = [objectContext executeFetchRequest:request error:&error];
// example for one section
data = [[NSMutableArray alloc] init];
NSMutableArray* ccurrentSection = [[NSMutableArray alloc] init];
[data addObject:currentSection];
for(Note* t in notes)
[currentSection addObject:t];
当视图加载时,前 5 个注释会显示(其余的不适合视图),一切正常。但是当我向下滚动查看下一个笔记时,我得到一个
NSObjectInaccessibleException 具有 ID... 的 NSManagedObject 已失效。
数组中的所有对象都会发生这种情况。
这怎么可能?我检查并没有重置/释放上下文。或者存储一个 Core Data 对象并在以后引用它是不是很糟糕?
编辑:如果我不滚动并且想要在选中笔记时显示有关笔记的详细信息,这似乎也会发生。似乎只要显示第一个注释,它们就会失效。
【问题讨论】:
-
您需要保留 managedObjectContext 还是在您的应用委托中完成 - 如果您的托管对象上下文消失,可能会导致此错误。
-
在应用程序委托中,我有 Xcode 自动创建的属性:@property (nonatomic, retain, readonly) NSManagedObjectContext* managedObjectContext;所以应该保留。我不会在任何地方发布它,也不会更改数据库。
标签: iphone objective-c database core-data ios