我已经使用另一个帖子来解决部分问题,所以现在我可以等待请求的结束了。我用Almofire发了一个http请求并解析生成的JSON文件。我认为myGroup.notify中的代码在请求完成后正确执行(如果我打印allCards.count则返回正确的值)。为什么我把for循环放在里面总是显示最后一张卡?
感谢您的帮助
import UIKit
mport SwiftyJSON
import Alamofire
class ViewController: UIViewController {
//variables Declaration
var allCard = [Card]()
let allCardsHTTP: String = "https://omgvamp-hearthstone-v1.p.mashape.com/cards?mashape-key="
override func viewDidLoad() {
super.viewDidLoad()
let myGroup = DispatchGroup()
//get HTTp request with Alamofire
myGroup.enter()
Alamofire.request(allCardsHTTP, method: .get).responseJSON {
response in
if response.result.isSuccess {
let jsonCards : JSON = JSON(response.result.value!)
print("success")
self.updateJSONCards(json: jsonCards)
}
else {
print("error")
}
myGroup.leave()
}
myGroup.notify(queue: .main) {
//Updte UI here
print(self.allCard[10].name) //This is Working
for card in self.allCard {
if card.cardsSet == "Basic" {
print(card.name)
}
} //For loop always showing last card ???
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - JSON Parsing
//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
//create the cards
for (set, value) in json {
var card = Card()
card.cardsSet = set
if json[set].count != 0 {
for i in 0...json[set].count - 1 {
card.name = json[set][i]["name"].stringValue
allCard.append(card)
}
}
else {
print("The set \(set) has no cards")
}
}
}
}
答案 0 :(得分:2)
您正在错误的位置创建Card
实例。
在内部重复循环之前,您正在创建一个实例,并将相同的实例附加到allCard
数组。如果Card
是一个类(引用语义),那么该实例的所有实例都包含相同的数据(最后一个循环项)。
将两行放在重复循环中。
//Write the updateJSONCards method here:
func updateJSONCards(json: JSON) {
//create the cards
for (set, value) in json {
if !json[set].isEmpty {
for i in 0..<json[set].count {
let card = Card()
card.cardsSet = set
card.name = json[set][i]["name"].stringValue
allCard.append(card)
}
}
else {
print("The set \(set) has no cards")
}
}
}