这些是我简单的类结构。我根据用户ID和状态拉取状态可能有也可能没有城市,城市可能有也可能没有拉链。这些是基于用户的设置方式。我成功地从我的网站检索数据,但是我在向城市和城市注入拉链时遇到了问题。我只能在表格视图中显示状态。尝试使用在屏幕上打印时,City和Zip对象为空。知道为什么我不能将城市和拉链注入州对象吗?
class State {
var id:Int
var name:String
var city:[City]?
init(id:Int, name:String, city:[City]?){
self.id = id
self.name = name
self.city = city
}
}
class City {
var id:Int
var name:String
var zip:[Zip]?
init(id:Int, name:String, zip:[Zip]?){
self.id = id
self.name = name
self.zip = zip
}
}
class Zip {
var id:Int
var name:String
init(id:Int, name:String){
self.id = id
self.name = name
}
}
我用它们用getStateCityZip()
方法生成表格视图。我从我的网站上提取数据。
// These are table view controller class properties
var state = [State]()
var city = [City]()
var zip = [Zip]()
override func viewDidLoad() {
super.viewDidLoad()
getStateCityZip()
}
func getStateCityZip(){
// Get States
getStatesByUserID(userID) {
(result)->() in
var states = JSON(result)
for index in 0... states.count - 1 {
let statesID: Int = states[index]["stateID"].intValue
let statesName: String = states[index]["title"].stringValue
// Get Cities by State ID
self.getCities(stateID) {
(result) -> () in
let cities = JSON(result)
for index in 0...cities.count - 1 {
let cityID: Int = cities[index]["cityID"].intValue
let cityName: String = cities[index]["title"].stringValue
// Get zip by city id
self.getZips(cityID){
(result) -> () in
var zips = JSON(result)
for zipIndex in 0... zips.count - 1 {
let zipID: Int = zips[zipIndex]["id"].intValue
let zipName: String = zips[zipIndex]["zipName"].stringValue
// Append single zip into zips array
self.zip.append(Zip(id: zipID, name: zipName))
}
}
//Append a single city into cities array
self.city.append(City(id: cityID, name: cityName, zip: self.zip))
}
}
// Append a single state that contains cities and zips into states array
self.state.append(State(id: stateID, name: stateName, city:self.city ))
}
}
self.tableView.reloadData()
}
这是我的表格视图cellForRowAtIndexPath
方法。我只能看到州名
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("StateCell", forIndexPath: indexPath) as! StateCityZipTableViewCell
let state = self.state[indexPath.row]
println(state.city?.count) // This prints 0
cell.label.text = "\(state.name)" // This displays state name in my tableview cell
return cell
}