I'm developing app using CLCircularRegion
.
I want to set value in CLCircularRegion
. So I did region.setValue(forKey:key)
but it showed
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)
}
}
"Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key bb"
Could I set value(url) in CLCircularRegion
??
Swift isn't Javascript - you can't create new properties on an existing class or struct, and neither CLCircularRegion
nor CLRegion
from which it inherits has properties msg
nor url
.
You have misconstrued what setValue
does - it is a method on the base class NSObject
which allows the setting of an existing property of the class by reference to its "name" or key. Its use is not recommended in Swift (it's an Objective-C legacy).
What you need to do is to create a struct or subclass that holds both your region and your required properties:
Either
struct MyRegion {
var region: CLCircularRegion
var msg: String
var url: String
}
or
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
}
}
p.s. don't use 'url' as the name of a property that isn't a URL
- call it 'urlString' or some such. I just used that to correspond to your question's terminology.