Reputation: 1443
This Fetch Request takes almost 10 seconds to execute on iPhone. The goal is to fetch 1 random thumbnail from each category. setting fetchlimit = 1 most of the times return the same thumbnail so I have to fetch all photos from each category.
Any ideas ?
[categoriesArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photos"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"place.subcategory.category == %@", object];
[request setPredicate:predicate];
NSError *error;
NSArray *photosManagedObjectsArray = [managedObjectContext executeFetchRequest:request error:&error];
NSUInteger randomIndex = arc4random() % [photosManagedObjectsArray count];
NSManagedObject *photoObject = [photosManagedObjectsArray objectAtIndex:randomIndex];
UIImage *photoImage = [UIImage imageWithData:[photoObject valueForKey:@"thumbnail"]];
UIImage *resizedImage = [photoImage imageCroppedToFitSize:CGSizeMake(IMAGE_WIDTH, IMAGE_HEIGHT)];
[imagesArray addObject:resizedImage];
[objectsArray addObject:photoObject];
}];
many thanks! Bill.
Upvotes: 0
Views: 554
Reputation: 11993
You don't need to pull all your objects into an array. Just change
NSArray *photosManagedObjectsArray = [managedObjectContext executeFetchRequest:request error:&error];`
NSUInteger randomIndex = arc4random() % [photosManagedObjectsArray count];
to this
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&error];
NSUInteger randomIndex = arc4random() % count;
Now use fetchOffset
to grab just the single object you need.
[request setFetchOffset:randomIndex];
[request setFetchLimit:1];
Upvotes: 3