0

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

4

1 回答 1

0

Several issues. Your setup with the arrays is not optimal. By creating two separate arrays with events and photos you are breaking the relationship.

The key here is to completely do away with these artefacts. You can fetch all events and keep them in an array, if you want, but of course it would be much more robust to use a NSFetchedResultsController to give you the objects.

If you use an array, all you need is the event array. If for your collection view datasource you need the number of photos for an event, it is as easy as event.photos.count.

You are doing a to of completely unnecessary operations in your setup routine:

E.g. you fetch all events, but then filter them in a loop into a new array. You could just use a predicate in your fetch request.

Also, you transform your photos NSSet into an array (which will have random order), which is also unnecessary. If you need you photos in order, something like a timestamp seems most appropriate.

于 2013-11-07T08:31:15.683 回答