When I first populate a view I do this:
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;
}
The DataManager's get method looks like this:
- (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;
}
That all works fine. The view is populated. The thumbnail tap method looks like this:
- (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
}
The problem is that sometimes when I tap on a cat thumbnail, I get this:
cat <Cat: 0x7fa450> (entity: Cat; id: 0x7b71f0 <x-coredata://7C904BD2-16AA-486D-8D1B-C2D0ABCCB6D4/Cat/p1> ; data: <fault>)
cat id: (null)
Because the cat id is null, the app crashes when I try to do something with it.
So the cat id is never null when I first retrieve the cat objects from CoreData and lay out the view. It's when I later tap one of the thumbnails that the data has become a fault, so that when I access the cat_id property, it is null. The CatThumbnailView retains the Cat entity:
@property (nonatomic, strong) Cat* cat;
Why does this happen, and what do I do about it?
*note - this doesn't happen every time I tap a thumbnail. I'd say it happens 10-20% of the time. The other 80-90% of the time the data is not a fault. Why????
[[CoreDataController sharedController] managedObjectContext]
return a disposable context, or is this context being held strongly by the manager? was this context reset at any point in time? – Aubrette