从完成语句中检索数据变量返回空白
问题描述:
我对iOS编程相当陌生,在使用完成语句中的变量时遇到了问题。我已经包含了下面的代码,我不知道为什么当我将完成变量存储在dataType数组中时,它似乎只返回空白字符串。从完成语句中检索数据变量返回空白
注:完成数据被称为在loadSampleStockData功能,它以后想返回到在FUNC的tableView(的tableView:UITableView的,的cellForRowAtIndexPath indexPath:NSIndexPath)细胞 - >的UITableViewCell
感谢您的帮助,可以提供!
import UIKit
class dashboardViewController: DefaultViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var balanceLabel: UILabel!
var stocks = [stockData]()
let stock = stockinfo()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
loadSampleStockData()
user.newUser() // Move to login function when login and registration is implemented
//Sets the Balance Label on Dashboard
balanceLabel.text = "$" + String(format: "%.2f", user.getBalance())
}
func loadSampleStockData() {
var stock1: stockData = stockData(name: "", askPrice: "", percentageChange: "", stockTicker: "")
var stock2: stockData = stockData(name: "", askPrice: "", percentageChange: "", stockTicker: "")
var stock3: stockData = stockData(name: "", askPrice: "", percentageChange: "", stockTicker: "")
stock.getInfo("FB") {(name, price, change) in dispatch_async(dispatch_get_main_queue(),{
stock1 = stockData(name: name, askPrice: price, percentageChange: change, stockTicker: "FB")
stocks.append(stock1)
})
}
stock.getInfo("MSFT") {(name, price, change) in dispatch_async(dispatch_get_main_queue(),{
stock2 = stockData(name: name, askPrice: price, percentageChange: change, stockTicker: "MSFT")
stocks.append(stock2)
})
}
stock.getInfo("APPL") {(name, price, change) in dispatch_async(dispatch_get_main_queue(),{
stock3 = stockData(name: name, askPrice: price, percentageChange: change, stockTicker: "APPL")
stocks.append(stock3)
})
}
print(stocks.count)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stocks.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "stockViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! stockTableViewCell
let stock = stocks[indexPath.row]
cell.stockName.text = stock.name
cell.stockPercentage.text = stock.percentageChange
cell.stockDollarChange.text = stock.askPrice
cell.stockTicker.text = stock.stockTicker
return cell
}
}
答
因为stocks += [stock1, stock2, stock3]
您的异步调用已设置stock1...3
任何东西之前发生。
创建stocks
应该在完成处理程序中完成。
感谢您的回应,可能是一个无知的问题,但是如果我在完成处理程序中启动库存,我不能在另一个完成处理程序中调用它们,因此因其变量范围而调用其他函数?因为我可能会误解你会介意提供一段代码片段吗?感谢您的帮助 –
您将需要共享状态,例如您在此处具有的实例变量。每个完成处理程序将异步添加到数组中,并且主线程将一直等到它们全部完成为止 – Alexander
非常感谢您的耐心,并花时间帮助我完成此任务。我试图在完成处理程序中将数据添加到“股票”中。我将如何着手将“股票”传递给完成处理程序。我上面做了我的更改,我是否正在讨论这个错误,如果是的话,你会介意给我一个代码片段。非常感谢您的帮助我将继续google和阅读文档 –