Ios 从核心数据中获取随机对象
我需要从核心数据文件中获取随机对象,比如10个随机对象 我该怎么做 这是我的Ios 从核心数据中获取随机对象,ios,core-data,nsfetchrequest,Ios,Core Data,Nsfetchrequest,我需要从核心数据文件中获取随机对象,比如10个随机对象 我该怎么做 这是我的NSFetchRequest设置 - (NSFetchRequest *)fetchRandom { if (!_fetchRandom) { _fetchRandom = [[NSFetchRequest alloc] init]; } [_fetchRandom setEntity:[NSEntityDescription entityForName:@"Contacts" inManagedObjectCo
NSFetchRequest
设置
- (NSFetchRequest *)fetchRandom
{
if (!_fetchRandom) {
_fetchRandom = [[NSFetchRequest alloc] init];
}
[_fetchRandom setEntity:[NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:self.oneManagedObjectContext]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"checked = %@", @"0"];
[_fetchRandom setPredicate:predicate];
NSUInteger count = [self.oneManagedObjectContext countForFetchRequest:_fetchRandom error:NULL];
NSUInteger random = (arc4random() % 5) + 3;
[_fetchRandom setFetchLimit:random];
return _fetchRandom;
}
您不能在此处获取10个随机对象。取而代之的是,通过将fetch limit设置为random,可以获取随机数量的对象 对于实际获取随机对象,您必须更改谓词 一种方法是将一个属性分配给实体,并将某个数字作为其值—比如说“sortKey”,在构建数据库时将其唯一地分配给每个对象 现在获取10个随机值,并将谓词更改为在这组10个随机值中返回带有sortKey的对象 将fetchlimit设置为10