Ich versuche, Daten von Firebase und Objekt meiner Daten sieht in JSON Form wie folgt zu analysieren:Array of Custom Modell ist Nil
"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
} ]
}
}
Meine ThingModel
wie folgt aussieht:
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
}
}
}
Und meine LocationModel
sieht wie folgt aus:
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
}
}
das Problem ist, dass wenn ich versuche, den anruf locations
Array in einer for-Schleife, das Array wird als null angesehen. Hier
ist der Code:
_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)
}
}
}
}
})
Zur Erinnerung, mein LocationModel
Array als Null zurückgeführt wird, und ich weiß nicht, warum. Jede Hilfe würde sehr geschätzt werden!
Ihre 'LocationModel' ist' nil' weil Ihr 'Wörterbuch [ "Location"]', dass es auch zu schaffen verwendet wird muss sei 'nil'. – NRitH
Und Sie sollten wirklich vermeiden, implizit-unwrapped Optionals zu verwenden, es sei denn, sie sind absolut notwendig (was normalerweise nicht der Fall ist) oder idiomatisch, wie '@ IBOutlet's. – NRitH
@NRitH Ja, ich verstehe das, aber wie komme ich damit klar? –