如何检索满足条件 swift 2 的 CoreData
How to retrieve CoreData that satisfies a condition swift 2
我有一个数据库,其中包含如下字段
纬度经度标志
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 TABLE_LOCATION 中检索所有记录,非常感谢任何代码或工作示例
谢谢!
您需要将 NSPredicate 添加到您的 fetchRequest。
fetchRequest.predicate = NSPredicate(format: "flag == %@", "3")
您可以使用 NSPredicate 并将其设置为 fetchRequest。在执行获取请求之前创建一个 NSPredicate 并将其设置为 fetchRequest。
fetchRequest.predicate = NSPredicate(format: "flag = 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 Table 作为参数与谓词一起传递以对其进行概括。
我有一个数据库,其中包含如下字段
纬度经度标志 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 TABLE_LOCATION 中检索所有记录,非常感谢任何代码或工作示例
谢谢!
您需要将 NSPredicate 添加到您的 fetchRequest。
fetchRequest.predicate = NSPredicate(format: "flag == %@", "3")
您可以使用 NSPredicate 并将其设置为 fetchRequest。在执行获取请求之前创建一个 NSPredicate 并将其设置为 fetchRequest。
fetchRequest.predicate = NSPredicate(format: "flag = 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 Table 作为参数与谓词一起传递以对其进行概括。