swift - 如何在 coredata 中同时使用谓词和排序描述符

标签 swift core-data

我正在使用“sortdescriptor”来获取“nsmutablearray”,它按创建日期排序,但问题不是按谓词过滤。我想同时应用排序和过滤器。我已尝试使用以下方法

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
    let sort = NSSortDescriptor(key: "date", ascending: false)
    let pre:NSPredicate = NSPredicate(format: "id == %d", 100)
    fetchRequest.predicate = pre
    fetchRequest.sortDescriptors = [sort]

最佳答案

你可以试试这个:-

change <Message> to your entityModel


let fetchRequest = NSFetchRequest<Message>.init(entityName: "Message")
fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "date", ascending: false)]
let predicate = NSPredicate.init(format: "id = %@","100")
fetchRequest.predicate = predicate

关于swift - 如何在 coredata 中同时使用谓词和排序描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025341/

相关文章:

ios - 如何在 WatchKit 扩展目标中获取核心数据持久存储路径

swift - 自引用实体,为了与 NSFetchedResultsController 建立父子关系

ios - 在 xib 中以编程方式自定义 UIView

ios - 在 WKWebView 中禁用缩放?

ios - 如何在 iOS 版 Google map 中添加自定义数据以叠加?

cocoa - Cocoa Touch 相当于 NSArrayController 吗?

iphone - iOS 崩溃 'NSInternalInconsistencyException',原因 : 'statement is still active' Core Data cache related?

ios - 与 WatchOS 共享 Realm 数据

ios - 静态 TableViewCell 的 TextView

iphone - 预填充的数据库。现在我想添加更多数据而不弄乱预先存在的数据