gpt4 book ai didi

arrays - 当我用 Swift 制作表格时,数组为空

转载 作者:行者123 更新时间:2023-11-30 13:40:14 24 4
gpt4 key购买 nike

因此,当我在获取数据函数中打印两个数组时,它具有我想要的值,但是,当我去创建 TableView 时,计数为零并且两个数组都是空的。在过去的几个小时里我一直在尝试解决这个问题,并且也尝试过 NSArrays。

var nameArray = [String]()
var textArray = [String]()

var urlStart = "https://api.deckbrew.com/mtg/cards?"


@IBOutlet weak var cardTitle: UILabel!
@IBOutlet weak var info: UITextView!

class Card: Mappable {
var name: String?
var store_url: String?
var text: String?
required init?(_ map: Map) {
}
func mapping(map: Map) {
name <- map["name"]
store_url <- map["store_url"]
text <- map["text"]
}
}



override func viewDidLoad() {
super.viewDidLoad()

func getData()
self.tableView.reloadData()

}


func getData() {

let myURLString = "https://api.deckbrew.com/mtg/cards/typeahead?q=sele"
let myURL = NSURL(string: myURLString)!

var myCardsArray = [Card]()



let mySession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let myDataTask = mySession.dataTaskWithURL(myURL) { (data, response, error) in
guard error == nil else {
print("There was error with the task")
return
}
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
for someCard in jsonData as! NSArray{
let card = Mapper<Card>().map(someCard)
myCardsArray.append(card!)

self.nameArray.append(card!.name!)
self.textArray.append(card!.text!)

}
} catch {
print("There was an error")
}
}

myDataTask.resume()
}



override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return nameArray.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : TableViewCell! = tableView.dequeueReusableCellWithIdentifier("Card") as! TableViewCell

cell.cardTitle.text = nameArray[indexPath.row] as! String
cell.cardInfo.text = textArray[indexPath.row] as! String

return cell as TableViewCell
}




override func didReceiveMemoryWarning() {

}}

最佳答案

使用异步方法获取数据后,您应该在此处重新加载表格 View :

 do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
for someCard in jsonData as! NSArray{
let card = Mapper<Card>().map(someCard)
myCardsArray.append(card!)

self.nameArray.append(card!.name!)
self.textArray.append(card!.text!)
//////// here
dispatch_async(dispatch_get_main_queue()...) {
self.tableView.reloadData()
}

}

关于arrays - 当我用 Swift 制作表格时,数组为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com