我正在尝试解析Firebase中的数据,我的数据对象看起来像JSON格式:
"Things" : {
"Blah1" : {
"Id" : 1,
"Location" : [ {
"DownVote" : 1,
"Latitude" : 42.36455,
"Longitude" : 71.05796,
"Time" : "rerwr",
"UpVote" : 1
}, {
"DownVote" : 3,
"Latitude" : 13.454,
"Longitude" : 213.343,
"Time" : "dfsadf",
"UpVote" : 1
} ]
}
}
我的ThingModel
看起来像这样:
public class ThingModel {
private var _id: Int!
private var _locationArray:[LocationModel]!
var id: Int {
return _pokedexId
}
var locations: [LocationModel] {
return _locationArray
}
init(dictionary: Dictionary<String, AnyObject>) {
if let id = dictionary["Id"] as? Int {
_id = id
}
if let locations = dictionary["Location"] as? [LocationModel] {
_locationArray = locations
}
}
}
我的LocationModel
看起来像这样:
private var Latitude: Double!
private var Longitude: Double!
private var UpVotes: Int!
private var DownVotes: Int!
private var Time: String!
private var ModelKey: String!
var locationCoordinate: CLLocationCoordinate2D {
let coordinate = CLLocationCoordinate2DMake(Latitude, Longitude)
return coordinate
}
var upVotes: Int {
return UpVotes
}
var downVotes: Int {
return DownVotes
}
var time: String {
return Time
}
init(key: String, dictionary: Dictionary<String, AnyObject>) {
self._modelKey = key
if let latitude = dictionary["Latitude"] as? Double {
self.Latitude = latitude
}
if let longitude = dictionary["Longitude"] as? Double {
self.Longitude = longitude
}
if let downVotes = dictionary["DownVote"] as? Int {
self.DownVotes = downVotes
}
if let upVotes = dictionary["UpVote"] as? Int {
self.UpVotes = upVotes
}
if let time = dictionary["Time"] as? String {
self.Time = time
}
}
问题是,当我尝试在for循环中调用locations
数组时,该数组被视为null。
以下是代码:
_REF_BASE.child("Things").observeEventType(.Value, withBlock: { snapshot in
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot]{
for snap in snapshots {
if let dict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let thingObject = thingModel(lobbyKey: key, dictionary: pokeDict)
for location in thingObject.locations {
let coord = location.locationCoordinate
let pin = MKPointAnnotation()
self.pinArray.append(pin)
pin.coordinate = coord
pin.title = thingObject.name
self.mapView.addAnnotation(pin)
}
}
}
}
})
总结一下,我的LocationModel
数组返回为零,我不知道为什么。
任何帮助将不胜感激!
答案 0 :(得分:1)
您必须首先获取“位置”词典数组,然后迭代它们并使用词典和&amp ;;初始化LocationModel
对象。关键价值观。转换为[LocationModel]
不会自动为您初始化LocationModel
个对象。
以下是ThingModel
的示例初始化程序,它将适当地初始化您的LocationModel数组,
init(dictionary: Dictionary<String, AnyObject>) {
if let things = dictionary["Things"] as? Dictionary<String, AnyObject> {
if let blah = things["Blah1"] as? Dictionary<String, AnyObject> {
if let id = blah["Id"] as? Int {
_id = id
}
if let locations = blah["Location"] as? [AnyObject] {
var locationModelArray: [LocationModel] = []
for location in locations {
locationModelArray.append(LocationModel(key: "key", dictionary: location as! Dictionary<String, AnyObject>))
}
_locationArray = locationModelArray
}
}
}
}