【问题标题】:Fetch Specific Number of Random Rows from CoreData从 CoreData 中获取特定数量的随机行
【发布时间】:2010-09-20 16:02:17
【问题描述】:

我正在使用下面的代码使用符合搜索条件的 CoreData 获取一组查询的所有行:itemType = 1。 但我需要做的是从数据中获取特定数量的随机行。 例如,我需要随机获取 dataType = 1 的 25 行,而不是检索列名 dataType = 1 的所有 100 行数据。 我希望有相对无痛的解决方案。 任何帮助表示赞赏。 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];

【问题讨论】:

    标签: iphone xcode core-data predicate fetch


    【解决方案1】:

    您实际上无法获取随机行。一个合理的随机化策略可能是获取与您的谓词匹配的所有对象,然后随机选择特定数量的对象。

    无论如何你可以使用NSFetchRequest的以下方法:

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

    基本上,setFetchLimit 允许您定义要获取的行数(在您的情况下,您将限制设置为 25),而 setFetchOffset 定义将开始返回行的偏移量(请参阅文档fetchOffset 属性了解详情)。

    这不是一个随机过程,但您可以随机生成偏移量。但是,值得注意的是,根据偏移量,您可能会获取一些介于零和获取限制之间的对象。

    【讨论】:

      【解决方案2】:

      您也可以使用参考方法。当您按观看次数排序时。 我很久以前就发过帖子了:http://www.alterplay.com/ios-dev-tips/2010/06/fetch-random-record-with-coredata.html 抱歉格式化。从 Blogger 切换到 Wordpress 后它坏了。

      【讨论】:

      • 你不能修复帖子或者删除它吗?
      猜你喜欢
      • 2017-10-27
      • 2021-12-22
      • 1970-01-01
      • 2018-03-25
      • 2014-05-16
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多