Reputation: 2669
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];
Upvotes: 4
Views: 2574
Reputation: 1207
You could also use reference approach. When you sort by view counts. I posted long time ago about it: http://www.alterplay.com/ios-dev-tips/2010/06/fetch-random-record-with-coredata.html Sorry for formatting. it's broken after switching from Blogger to Wordpress.
Upvotes: -3
Reputation: 25429
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.
Upvotes: 5