我通常会像下面的例子一样创建一个NSObject,让firebase观察单个事件调用来获取数据,然后我会创建一个NSObject的实例并简单地在NSObject上调用setValueForKeys方法,然后传入值我可以轻松地使用if let语句来获取我需要的特定数据。自从我从swift 3.1升级到swift 4.0.2后,这已停止工作,请参阅下面的代码片段。自从新的更新以来,我相信我做错了。因为它需要的键值确实存在,如NSObject声明和打印输出中所示。任何建议将不胜感激。
class BarberMarker: NSObject {
var companyID: String?
var companyName: String?
var companyLogoImageUrl: String?
var companyLogoImage: UIImage?
var companyFormattedAddress: String?
var companyAddressLongitude: String?
var companyAddressLatitude: String?
var distanceFromCurrentUser: Double?
var dateCreated: String?
var timezone: String?
var calendar: String?
var local: String?
var ratingValue: CGFloat?
}
firebase调用从数据库中获取数据
func getAllMarkers(){
firebaseRef.child("barberMarkers").observeSingleEvent(of: .value, with: { (snapshotssshhh) in
if let dictionary = snapshotssshhh.value as? [String: AnyObject] {
for marker in dictionary {
if let locMarker = marker.value as? [String: AnyObject] {
var markerB = BarberMarker()
print(locMarker)
markerB.setValuesForKeys(locMarker)
self.barbermarkers.append(markerB)
guard let lon = markerB.companyAddressLongitude, let lat = markerB.companyAddressLatitude else {
return
}
let latitude = (lat as NSString).doubleValue
let longitude = (lon as NSString).doubleValue
let locValue:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
DispatchQueue.main.async{
let desiredMarker = GMSMarker(position: locValue)
desiredMarker.icon = GMSMarker.markerImage(with: UIColor(r: 118, g: 187, b: 220))
desiredMarker.map = self.mapView
self.bMarkers.append(desiredMarker)
}
}
}
}
}, withCancel: nil)
}
我收到错误消息
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<maizewars.BarberMarker 0x7fb62ff5f5b0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key companyAddressLongitude.'
答案 0 :(得分:3)
试试这个兄弟。
@objcMembers class BarberMarker: NSObject {
...
}
原因@objcMembers在Swift 4中使用
当Swift类引入许多需要 Objective-C 运行时行为的新方法或属性时,请在该类的声明中使用@objcMembers属性。
将@objcMembers属性应用于类会隐式地将@objc属性添加到其所有与Objective-C兼容的成员。
因为应用@objc属性会增加应用程序的编译大小并对性能产生负面影响,所以只有在每个成员都需要应用@objc属性时才对声明应用@objcMembers属性。