【问题标题】:Could I set value in CLCircularRegion?我可以在 CLCircularRegion 中设置值吗?
【发布时间】:2023-03-05 05:16:01
【问题描述】:

我正在使用CLCircularRegion 开发应用程序。

我想在CLCircularRegion 中设置值。所以我做了region.setValue(forKey:key) 但它显示了

        if CLLocationManager.locationServicesEnabled() {
            for obj in pushInfoArr! {
                let localLatiStr = obj["local_latit"] as! String
                let localLongitStr = obj["local_longit"] as! String
                let localMsg = obj["local_mesg"] as! String
                let url = obj["cnnct_url"] as! String
                let localLati = Double(localLatiStr)
                let localLongi = Double(localLongitStr)
                let center = CLLocationCoordinate2DMake(localLati!, localLongi!)
                region = CLCircularRegion(center: center, radius: 1000, identifier: localMsg)
                region.setValue(localMsg, forKey: "msg")
                region.setValue(url, forKey: "url")
                region.notifyOnEntry = true
                self.locationManager.startMonitoring(for: region)
            }
    }

“由于未捕获的异常'NSUnknownKeyException'而终止应用程序, 原因: '[ setValue:forUndefinedKey:]:这个类不是键值 密钥 bb 的编码兼容”

我可以在CLCircularRegion中设置值(url)吗??

【问题讨论】:

  • 请显示您正在使用的代码。你想设置什么值?边界框(“bb”)?您可以简单地通过clRegion.radius = 123.4 设置半径 - 类似的中心。见这里developer.apple.com/documentation/corelocation/clcircularregion
  • 更新问题!我想设置 url 和 message 来显示通知。当我通过通知运行应用程序时,我想转到保存的 url
  • 据我所知,它所继承的 CLCircularRegionCLRegion 都没有属性 msgurl - 所以你不能使用 setValue 来设置这些属性。

标签: swift swift4 clcircularregion


【解决方案1】:

Swift 不是 Javascript - 您不能在现有的类或结构上创建新属性,它所继承的 CLCircularRegionCLRegion 都没有属性 msgurl

你误解了setValue 的作用——它是基类NSObject 上的一个方法,它允许通过引用类的“名称”或键来设置类的现有 属性.不建议在 Swift 中使用它(它是 Objective-C 的遗留物)。

你需要做的是创建一个结构体或子类来保存你的区域和你需要的属性:

要么

struct MyRegion {
    var region: CLCircularRegion
    var msg: String
    var url: String
}

class MyRegion: CLCircularRegion {
    var msg: String
    var url: String
    init(centre: CLLocationCoordinate2D, radius: Double, identifier: String, msg: String, url: String) {
        super.init(centre: centre, radius: radius, identifier: identifier)
        self.msg = msg
        self.url = url
    }
}

附言不要使用 'url' 作为不是 URL 的属性的名称 - 将其称为 'urlString' 或类似名称。我只是用它来对应你问题的术语。

【讨论】:

    【解决方案2】:

    不,CLCircularRegion 没有名为 url 的属性,因此您不能在该类型的对象上设置 url。

    【讨论】:

    • 无法保存网址?只有标识符可用吗?
    猜你喜欢
    • 1970-01-01
    • 2020-02-20
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多