ios - 带有函数参数的 CoreData 谓词

标签 ios swift core-data nspredicate cllocation

我正在尝试在 Predicate 定义中包含一个函数。这可能吗?

假设您有一个 Places 的核心数据实体,其属性为 纬度和经度。

我想在一个 map View 中添加注释 距用户位置的指定距离。当然,我可以遍历整个数据库并计算每个 Place 和 用户位置,但我将有大约 35000 个位置,看起来 在中有一个谓词会更有效率 fetchedResultsController 设置。

I tried the code below but I receive an error message of "Problem with subpredicate BLOCKPREDICATE(0x2808237b0) with userInfo of (null)"

func myDistanceFilter(myLat : CLLocationDegrees, myLong : CLLocationDegrees, cdLat : CLLocationDegrees, cdLong : CLLocationDegrees) -> Bool {

    let myLocation = CLLocation(latitude: myLat, longitude: myLong)
    let cdLocation = CLLocation(latitude: cdLat, longitude: cdLong)

    if myLocation.distance(from: cdLocation) < 5000.0 {
        return true
    } else {
        return false
    }
}//myDistancePredicate

在 fetchedResultsController 中:

let distancePredicate = NSPredicate {_,_ in self.myDistanceFilter(myLat: 37.774929, myLong: -122.419418, cdLat: 38.0, cdLong: -122.0)}

如果可以在谓词中包含 block /函数,您如何获取对正在评估的实体对象的属性的引用?

如有任何指导,我们将不胜感激。

最佳答案

对其他遇到类似问题的人的额外观察。

考虑到上面 pbasdf 和 Jerry 的建议,至少在我的情况下,没有理由认为区域必须是圆形的。我将起草一个名称,表示一个近乎矩形的区域。我用纬度和经度值运行了一些测试。这些纬度和经度值可以缩放为一个矩形,该矩形包含用户指定的圆形半径。芝加哥纬度的一度约为 69 英里,一度经度约为 51 英里。我使用了以下内容:

var myUserLatitude : CLLocationDegrees!
var myUserLongitude : CLLocationDegrees!

在 View 的初始化文件中:

guard let userLatitude = locationManager.location?.coordinate.latitude else {return}
guard let userLongitude = locationManager.location?.coordinate.longitude else {return}
myUserLatitude = userLatitude
myUserLongitude = userLongitude

在 fetchedResultsController 变量创建中:

let latitudeMinPredicate = NSPredicate(format: "latitude >= %lf", myUserLatitude - 1.0)
let latitudeMaxPredicate = NSPredicate(format: "latitude <= %lf", myUserLatitude + 1.0)
let longitudeMinPredicate = NSPredicate(format: "longitude >= %lf", myUserLongitude - 1.0)
let longitudeMaxPredicate = NSPredicate(format: "longitude <= %lf", myUserLongitude + 1.0)

var compoundPredicate = NSCompoundPredicate()
compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [anotherUnrelatedPredicate,latitudeMinPredicate,latitudeMaxPredicate,longitudeMinPredicate, longitudeMaxPredicate])
fetchRequest.predicate = compoundPredicate        

显然,我将创建另一个属性来缩放每个用户所需区域的 1.0 值。初步测试似乎有效,最重要的是我不敢相信它有多快。从字面上看,tableView 是在 viewController 转到封闭的 mapView 时填充的。

关于ios - 带有函数参数的 CoreData 谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55467025/

相关文章:

ios - 如何在 iOS 下使用设备上的 CoreAudio 以编程方式创建一定长度的空 .m4a 文件?

javascript - 为什么 paper.js 路径创建在 iOS 设备上不起作用?

ios - Swift Core Data 多对多关系处理,代码生成为手动/无

swift - 在进行 POST 之前等待找到坐标

ios - 背景中的位置不起作用

ios - 核心数据崩溃获取

ios - 重新加载数据 VS。 reloadRowsAtIndexPaths

iOS Admob Interstitial 广告卡住并变得无响应

ios - swift : show another view controller on swipe up in first view controller

ios - 自定义子类中的变量不会保存/不会从核心数据加载