开发者

CoreData - how to create fetchrequest to get array of random attribute values

I have simple model with 2 entities House and Flat. House has to many relation to Flat. Flat has attributes like number and description.

I would like to get a list of random eight flat numbers.

I'm trying to go this way, but it seems that' wrong

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"House" inManagedObjectContext:self.managedObjectContext];

    [fetchRequest setEntity:entity];

    [fetchRequest setFetchBatchSize:20];

    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];

    NSArray *houses = [aFetchedResultsController fetchedObjects];

Then I need to get appropriate values.

Please show me a right approach.

I try to answer myself. Perhaps my brains are dry:) Just need

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flat" inManagedObjectContext:self.managedObjectContext开发者_如何学编程];

and then work with array of fetched objects. But I'm steel believe that there is more elegant solution.

I have further question related to the first one. How to get random objects if number of flats is about 10000? In general it works but slows down noticeable.


LimitSort the records randomly and set [fetchRequest setFetchLimit:8]; to get the first eight. For random sorting make a NSSortDescriptor with selector or comparator that returns NSComparisonResult randomly and add this descriptor to the fetch request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜