在我正在处理的项目的表格视图中,我一直在努力正确显示用户输入的值。
我获取用户输入值的方式是让用户在文本字段中输入信息(公司名称,股票代码和徽标的URL),然后在按下完成按钮时调用handleSave()
:
func handleSave() {
let newCompanyName = nameTextField.text
guard let newCompanyStockSymbol = stockTextField.text else {
// handle the error how you see fit
print("error getting text from field")
return
}
let newCompanyLogo = logoTextField.text
var newCompanyStockPrice = ""
// Fetch stock price from symbol provided by user for new company
let url = URL(string: "https://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20Ask%2C%20YearHigh%2C%20YearLow%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22\(newCompanyStockSymbol)%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
} else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
let json = JSON(data: data!)
if let quotes = json["query"]["results"]["quote"].array {
for quote in quotes {
let ask = quote["Ask"].stringValue
newCompanyStockPrice = ask
}
}
}
self.viewController?.save(name: newCompanyName!, logo: newCompanyLogo!, stockPrice: newCompanyStockPrice)
//self.viewController?.tableView.reloadData()
}
task.resume()
let cc = UINavigationController()
let companyController = CompanyController()
cc.viewControllers = [companyController]
present(cc, animated: true, completion: nil)
}
反过来调用此save
函数,该函数将值保存到托管上下文中。
func save(name: String, logo: String, stockPrice: String) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
let entity =
NSEntityDescription.entity(forEntityName: "Company",
in: managedContext)!
let company = NSManagedObject(entity: entity,
insertInto: managedContext)
company.setValue(stockPrice, forKey: "stockPrice")
company.setValue(name, forKey: "name")
company.setValue(logo, forKey: "logo")
do {
try managedContext.save()
companies.append(company)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
tableView.reloadData()
}
如果我在self.viewController?.save(name: newCompanyName!, logo: newCompanyLogo!, stockPrice: newCompanyStockPrice)
函数中调用handleSave()
时设置了断点,我可以看到所有这三件事(newCompanyName
,newCompanyLogo
和{{1} })有价值。但是当我尝试在newCompanyStockPrice
中设置它时,新公司不会出现在我的表格视图中:
cellForRow
编辑:override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return companies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! Cell
let company = companies[indexPath.row]
let stock = company.value(forKey: "stockPrice") as? String
// Company name labels
cell.textLabel?.text = company.value(forKey: "name") as? String
// Stock price underneath
if let stock = stock {
cell.detailTextLabel?.text = "Current stock price: \(stock)"
}
// Logos
DispatchQueue.main.async {
if let url = NSURL(string: (company.value(forKey: "logo") as? String)!) {
if let data = NSData(contentsOf: url as URL) {
cell.logoView.image = UIImage(data: data as Data)
} else {
cell.logoView.image = UIImage(named: "noImage")
}
}
}
return cell
}
viewWillAppear
答案 0 :(得分:0)
我建议将调用放在主队列上显式重新加载数据。在我看来,您正在func save(name: String, logo: String, stockPrice: String)
完成处理程序中调用dataTask
,然后在该线程上调用reloadData
。
因此,在save
函数中,将其包装成如下:
DispatchQueue.main.async { [weak self] in
self?.tableView.reloadData()
}