【问题标题】:Core Data - Predicate to-many objects核心数据 - 多对象谓词
【发布时间】:2014-02-11 20:44:46
【问题描述】:

我有一个困难的提取查询,我不知道如何执行,
我的核心数据模型:

Artis
-----
name

songs -> (to-many relationship to Song Object)

Song
-----
title
release_Date

artist -> (to-one relationship to Artist Object)

我需要一个谓词来获取拥有最多歌曲(以及至少 2 首歌曲)的 5 位顶级艺术家,并且所有歌曲的 release_Date 必须在过去 30 天内。

【问题讨论】:

    标签: ios iphone objective-c core-data nsfetchedresultscontroller


    【解决方案1】:

    你需要结合:

    // Predicate for date at least 30 days back
    
    NSDate *date = [NSDate date];
    NSDate *date30daysBack = [date dateByAddingTimeInterval:-60*60*24*30];
    
    [NSPredicate predicateWithFormat: @"song.release_date >= %@", date30daysBack];
    
    // Predicate for at least 2 songs
    
    [NSPredicate predicateWithFormat: @"songs.@count >= 2"];
    
    // Sort descriptor for most songs
    
    //EDIT
    //Sorting should be done after the fetch request.
    
    // Set the fetchLimit of your NSFetchRequest to 5
    request.fetchLimit = 5;
    

    【讨论】:

    • 备注:不是每天都有60*60*24秒(夏令时转换的事情)。
    • 正确,日期应使用NSDateComponents
    • 感谢您的回答,有 2 个问题: 1. 我可以用一个谓词和 AND 来做前两个谓词吗? 2. 有没有办法使用谓词或一些表达式来做前 5 名?
    • 1.可以,如果您希望所有歌曲的发布日期 >= 30 天前的日期,请使用 ALL songs.release_Date >= %@。 2. 不,这只有在你有 sqlite 持久存储时才有效。
    • 嗨,我认为排序描述符有问题,我无法将排序 @count 添加到 NSFetchRequest。我可以进行提取和排序,但这不会那么有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多