OGeek|极客世界-中国程序员成长平台

标题: ios - 从 Core Data 中获取随机对象 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:58
标题: ios - 从 Core Data 中获取随机对象

我需要从核心数据文件中获取随机对象,比如 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;
}



Best Answer-推荐答案


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

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

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

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

setFetchLimit 为 10。

关于ios - 从 Core Data 中获取随机对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905897/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4