【问题标题】:Fetch random objects from Core Data从 Core Data 中获取随机对象
【发布时间】:2014-07-23 08:48:29
【问题描述】:

我需要从核心数据文件中获取随机对象,比如 10 个随机对象。

我该怎么做?

这是我的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;
}

【问题讨论】:

    标签: ios core-data nsfetchrequest


    【解决方案1】:

    您没有在这里获取 10 个随机对象。相反,通过将获取限制设置为 random ,您正在获取随机数量的对象。

    要实际获取随机对象,您必须更改谓词。

    一种方法是为实体分配一个属性,并以某个数字作为其值——比如“sortKey”,在构建数据库时将其唯一地分配给每个对象。

    现在获取 10 个随机值并更改您的谓词以在这组 10 个随机值中返回带有 sortKey 的对象。

    setFetchLimit 为 10。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多