i'm doing practice, , find class property(adnames) can't assigned. can assigned outside(the place comment out). here code:
import uikit import alamofire import swiftyjson class adtableviewcontroller: uitableviewcontroller { var adnames: [json]? override func viewdidload() { super.viewdidload() alamofire.request(.get, "http://codewithchris.com/code/afsample.json").responsejson { (response) -> void in if let value = response.result.value{ let json = json(value) print(json["secondkey"].arrayvalue) //["item1","item2","item3"] self.adnames = json["secondkey"].arrayvalue } } // self.adnames = ["item1", "item2", "item3"] } override func tableview(tableview: uitableview, numberofrowsinsection section: int) -> int { if let names = adnames { return names.count } return 0 } override func tableview(tableview: uitableview, cellforrowatindexpath indexpath: nsindexpath) -> uitableviewcell { ... } }
can tell me reason? thanks!
your alamofire request runs in background. meanwhile, tableview wants display , calls numberofrowsinsection. time, alamofire has not finished work, adnames hasn't been set.
you need refresh tableview reloaddata()
after adnames set. i.e.
alamofire.request(.get, "http://codewithchris.com/code/afsample.json").responsejson { (response) -> void in if let value = response.result.value{ let json = json(value) self.adnames = json["secondkey"].arrayvalue self.tableview.reloaddata() } }
then tableview refresh , re-call numberofrowsinsection, , @ time, adnames not nil.
Comments
Post a Comment