核心数据对象失效

时间:2010-12-10 11:41:27

标签: iphone objective-c database core-data ios

我遇到了一些以某种方式无效的Core Data对象的问题。 托管对象上下文位于app委托中,我在视图表中使用它来从数据库中获取“notes”对象并显示它们。 我为这些部分(今天,昨天等)构建了一个数组,并为每个部分创建了一个数组,其中的部分内容如下:

// 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对象并在以后引用它是不是很糟糕?

编辑:如果我不滚动并希望在选中时显示有关注释的详细信息,这似乎也会发生。似乎一旦显示第一个音符,它们就会失效。

1 个答案:

答案 0 :(得分:1)

它似乎与管理notes对象的方式有关,但执行此操作的代码不在您的示例中。 notes数组是一个autorelease数组,所以除非你把它保留在某处,否则它可能会在你加载下一部分之前释放它。