When I first fill out the 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 getManager DataManager method is as follows:
- (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; }
Everything works perfectly. The view is populated. The thumbnail click method is as follows:
- (void)thumbnailTapped:(UITapGestureRecognizer*)tap { CatThumbnailView* thumb = (CatThumbnailView*)tap.view; DLog(@"cat %@", thumb.cat); DLog(@"cat id: %@", thumb.cat.cat_id);
The problem is that sometimes, when I click on the cat thumbnail, I get the following:
cat <Cat: 0x7fa450> (entity: Cat; id: 0x7b71f0 <x-coredata://7C904BD2-16AA-486D-8D1B-C2D0ABCCB6D4/Cat/p1> ; data: <fault>) cat id: (null)
Since the cat id is null, the application crashes when I try to do something with it.
Therefore, the cat identifier is never null when I first retrieve the cat objects from CoreData and lay out the view. This is when I later touch one of the thumbnails that the data has become an error, so when I access the cat_id property, it is zero. CatThumbnailView saves the Cat object:
@property (nonatomic, strong) Cat* cat;
Why is this happening, and what should I do about it?
* note - this does not happen every time I click a thumbnail. I would say that this happens in 10-20% of cases. Other 80-90% of the time data is not an error. Why????