【问题标题】:How to retrieve CoreData that satisfies a condition swift 2如何快速检索满足条件的CoreData 2
【发布时间】:2016-03-28 12:46:22
【问题描述】:

我有一个带有如下字段的数据库

纬度经度标志 54.1425 98.2564 0 52.1036 94.1458 3 51.1569 92.1458 3 50.1326 91.1458 3 56.1236 93.1458 0

我需要检索标志为 3 的记录。

    let fetchRequest = NSFetchRequest()

    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext

    let entityDescription = NSEntityDescription.entityForName("TABLE_LOCATION", inManagedObjectContext: managedContext)




    // Configure Fetch Request
    fetchRequest.entity = entityDescription


    do {
        let result = try managedContext.executeFetchRequest(fetchRequest)
        //print(result)


    } catch {
        let fetchError = error as NSError
        print(fetchError)
    }

我所拥有的只是上面的代码,它从表 TABLE_LOCATION 中检索所有记录,非常感谢任何代码或工作示例

谢谢!

【问题讨论】:

    标签: swift core-data swift2 nsfetchrequest executefetchrequest


    【解决方案1】:

    您需要将 NSPredicate 添加到您的 fetchRequest。

    https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSPredicate_Class/

    fetchRequest.predicate = NSPredicate(format: "flag == %@", "3")
    

    【讨论】:

      【解决方案2】:

      您可以使用 NSPredicate 并将其设置为 fetchRequest。在执行获取请求之前创建一个 NSPredicate 并将其设置为 fetchRequest。

      fetchRequest.predicate = NSPredicate(format: "flag = 3")
      

      【讨论】:

        【解决方案3】:

        将您的功能更改为:

        func fetchDistinctDataUsingReq(predicate :NSPredicate) -> NSArray {
           let fetchRequest = NSFetchRequest()
           fetchRequest.predicate = predicate
           //Rest of your code
        }
        

        现在调用这个函数:

        let predicate = NSPredicate(format: "flag == %@", 3)
        self.fetchDistinctDataUsingReq(predicate)
        

        这是一种更好的方法,可以在整个抓取过程中重复使用。此外,您可以将 CoreData 表作为参数与谓词一起传递以对其进行概括。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-29
          • 2023-02-25
          • 1970-01-01
          • 2014-01-21
          相关资源
          最近更新 更多