当我第一次填充视图时,我这样做:
self.cats = [[DataManager sharedManager] getCatsFromCoreData]; //cats is an NSArray property (strong)
for (Cat* cat in self.cats)
{
CatThumbnailView *thumb = [CatThumbnailView catThumbnailView];
thumb.cat = cat;
UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(thumbnailTapped:)];
[thumb addGestureRecognizer:tap];
[thumb setText:[cat.name uppercaseString]];
...
[self.someScrollview addSubview:thumb];
yPos += thumb.frame.size.height + spacing;
}
DataManager 的 get 方法如下所示:
- (NSArray*)getCatsFromCoreData
{
NSManagedObjectContext *context = [[CoreDataController sharedController] managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Cats" inManagedObjectContext:context]];
[request setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES]]];
NSError *error = nil;
NSArray *fetchedCats = [context executeFetchRequest:request error:&error];
if (fetchedCats.count > 0) {
return fetchedCats;
}
return nil;
}
这一切都很好。视图已填充。缩略图点击方法如下所示:
- (void)thumbnailTapped:(UITapGestureRecognizer*)tap
{
CatThumbnailView* thumb = (CatThumbnailView*)tap.view;
DLog(@"cat %@", thumb.cat);
DLog(@"cat id: %@", thumb.cat.cat_id);
//do stuff here with the cat data
}
问题是,有时当我点击猫的缩略图时,我会得到以下信息:
cat <Cat: 0x7fa450> (entity: Cat; id: 0x7b71f0 <x-coredata://7C904BD2-16AA-486D-8D1B-C2D0ABCCB6D4/Cat/p1> ; data: <fault>)
cat id: (null)
因为 cat id 为空,所以当我尝试使用它做某事时,应用程序会崩溃。
因此,当我第一次从 CoreData 检索 cat 对象并布置视图时,cat id 永远不会为空。当我稍后点击其中一个缩略图时,数据已成为错误,因此当我访问 cat_id 属性时,它为空。CatThumbnailView 保留了 Cat 实体:
@property (nonatomic, strong) Cat* cat;
为什么会发生这种情况,我该怎么办?
*注意 - 每次我点击缩略图时都不会发生这种情况。我会说它发生在 10-20% 的时间里。其他 80-90% 的时间数据不是故障。为什么????