views:

60

answers:

1

I'm using the code below to Fetch a queried set of all rows using CoreData matching the search criteria: itemType = 1. But what I need to do is to Fetch a specific number of Random rows from the data instead. For example, instead of retrieving all 100 rows of data in which the column name dataType = 1, I need to get 25 rows randomly in which dataType = 1. I'm hoping there is relatively painless solution. Any help is appreciated. lq

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

[request setEntity:[NSEntityDescription entityForName:@"MyAppName" 
                    inManagedObjectContext:[self managedObjectContext]]];

NSError *error = nil;                                           
NSPredicate *predicate;
NSArray *fetchResults;
predicate = [NSPredicate predicateWithFormat:@"(itemType = %i)", 1];            
[request setPredicate:predicate];
fetchResults = [managedObjectContext executeFetchRequest:request error:&error];

if (!fetchResults) {
        // NSLog(@"no fetch results error %@", error);
}

self.mutableArrayName = [NSMutableArray arrayWithArray:fetchResults];
[request release];
A: 

You can not actually fetch random rows. A reasonable randomization strategy may be to fetch all of the objects matching your predicate, and then randomly select a specific number of objects.

Anyway you can use the following methods of NSFetchRequest:

- (void)setFetchLimit:(NSUInteger)limit
- (void)setFetchOffset:(NSUInteger)limit

Basically, setFetchLimit allows you to define how many rows you want to fetch (in your case you will set limit to 25), while setFetchOffset defines the offset at which rows will begin being returned (see the documentation of the fetchOffset property for details).

This is not a random process, but you may randomly generate the offset. However, it is worth noting here that, depending on the offset, you may then fetch a number of objects falling between zero and your fetch limit.

unforgiven