I have two entities with relationship. One parent and child(to many). The first time I fetch it is ok. The second time a fetch request is called the reference key to the parent gets removed/null which orphans the child record.
- (void)prepareGallery
{
self.events = [[NSMutableArray alloc] init];
self.photos = [[NSMutableArray alloc] init];
NSArray *tempArr = [self fetchEntity:@"PEvent" predicate:nil];
for (Event *pEvent in tempArr) {
NSSet *photoSet = [pEvent photos];
NSArray *photosArray = [photoSet allObjects];
if ([photosArray count] > 0) {
//only add events with photos
[self.events addObject:pEvent];
[self.photos addObject:photosArray];
}
}
if ([self.events count] > 0) {
[collectionView reloadData];
}else{
NSLog(@"Events empty");
}
}
-(NSArray*)fetchEntity:(NSString*) entityName predicate:(NSPredicate*) predicate
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
request.resultType = NSManagedObjectResultType;
if (predicate != nil) {
request.predicate = predicate;
}
NSError *error;
NSArray *result = [_managedObjectContext executeFetchRequest:request error:&error];
return result;
}
Model Relationship
Entity: Photo
Destination: PEvent
Inverse: photos
Delete Rule: no action
Type: To one
Entity: PEvent
Destination: Photo
Inverse: pEvent
Delete Rule: cascade
Type: To many