• 欢迎光临~

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

开发技术 开发技术 2022-12-13 次浏览

主要是使用 fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "key", ascending: true)]来进行排序
效果如下
Swift使用Core Data查询排序的方法

        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```
程序员灯塔
转载请注明原文链接:Swift使用Core Data查询排序的方法
喜欢 (0)