Swift使用Core Data查询排序的方法

主要是使用 fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "key", ascending: true)]来进行排序
效果如下

        let app = UIApplication.shared.delegate as! AppDelegate
        let context = app.persistentContainer.viewContext
        //声明数据的请求
        let fetchRequest = NSFetchRequest<FlagList>(entityName:"FlagList")
        //fetchRequest.fetchLimit = 10 //限定查询结果的数量
        //fetchRequest.fetchOffset = 0 //查询的偏移量
         //print("枚举值",platform.rawValue)
        //let platformvalue = platform.rawValue
        //设置查询条件//使用%@对应数字,字符串,日期的替代值
        //var sort = NSSortDescriptor(key: "key", ascending: true)
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "key", ascending: true)]
        let predicate = NSPredicate(format: " platform=%@ ",plat)
        fetchRequest.predicate = predicate
        var list = [FlagList]()
        //查询操作
        do {
            let fetchedObjects = try context.fetch(fetchRequest)
            //遍历查询的结果
            for info in fetchedObjects{
                print("查询结果",info.key)
                //print("platform=",info.platform)
                list.append(info)
            }
            
        }
        catch {
            fatalError("不能保存:\(error)")
        }
        return list```
posted @   Sqsdhc  阅读(185)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程
点击右上角即可分享
微信分享提示