在表格视图中标签打印到错误的单元格

时间:2017-01-24 18:00:39

标签: ios swift uitableview core-data

我使用Alamofire和SwiftyJSON从YQL获取股票,将它们保存到我的核心数据"公司"对象,然后使用标签中的数据,如:

尝试过的代码:

func fetchStocks() {

let entity = NSEntityDescription.entity(forEntityName: "Company", in: managedContext)!
var prices = [String]()

if let data = try? Data(contentsOf: 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(%22AAPL%22%2C%22GOOG%22%2C%22TWTR%22%2C%22TSLA%22%2C%20%22FB%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys")!) {
    let json = JSON(data: data)
    print(json)
    if let appleStockPrice = json["query"]["results"]["quote"][0]["Ask"].string {
        prices.append(appleStockPrice)
    }
    if let googleStockPrice = json["query"]["results"]["quote"][1]["Ask"].string {
        prices.append(googleStockPrice)
    }
    if let twitterStockPrice = json["query"]["results"]["quote"][2]["Ask"].string {
        prices.append(twitterStockPrice)
    }
    if let teslaStockPrice = json["query"]["results"]["quote"][3]["Ask"].string {
        prices.append(teslaStockPrice)
    }
    if let facebookStockPrice = json["query"]["results"]["quote"][4]["Ask"].string {
        prices.append(facebookStockPrice)
    }
    for stocks in prices {
        let company = NSManagedObject(entity: entity,insertInto: managedContext)
        company.setValue(stocks, forKey: "stockPrice")
        companies.append(company)
    }
    do {
        try managedContext.save()
        vc.tableView.reloadData()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
}
}

当我尝试使用

将价格设置为详细文本标签时
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! Cell
    let company = companies[indexPath.row]


    cell.textLabel?.text = company.value(forKey: "name") as? String

    cell.detailTextLabel?.text = "Current stock price: \(company.value(forKey: "stockPrice") as? String)"

    return cell
}

我明白了:

enter image description here

所以股票价格上涨了,但没有被公司放在细胞中 - 相反,这些价值是零,股票价格进入不同的细胞。

为什么会发生这种情况,我该如何解决?

编辑:发布了整个cellForRow方法,这里是YQL JSON:

{
  "query" : {
"created" : "2017-01-24T18:12:06Z",
"results" : {
  "quote" : [
    {
      "symbol" : "AAPL",
      "YearLow" : "89.470",
      "YearHigh" : "120.810",
      "Ask" : "119.990"
    },
    {
      "symbol" : "GOOG",
      "YearLow" : "663.06",
      "YearHigh" : "824.87",
      "Ask" : "821.70"
    },
    {
      "symbol" : "TWTR",
      "YearLow" : "13.73",
      "YearHigh" : "25.25",
      "Ask" : null
    },
    {
      "symbol" : "TSLA",
      "YearLow" : "141.0500",
      "YearHigh" : "269.3400",
      "Ask" : "253.4100"
    },
    {
      "symbol" : "FB",
      "YearLow" : "94.23",
      "YearHigh" : "133.50",
      "Ask" : "128.67"
    }
  ]
},
"count" : 5,
"lang" : "en-us"
  }
}

编辑2:设置名称,徽标和& stockPrices

func setDefaultCompanies() {

    // Default 5 companies at launch - user can delete/add/edit

    let userDefaults = UserDefaults.standard
    let defaultValues = ["firstRun" : true]
    userDefaults.register(defaults: defaultValues)

    if userDefaults.bool(forKey: "firstRun") {

        let entity = NSEntityDescription.entity(forEntityName: "Company", in: managedContext)!
        let defaultCompanies = ["Apple", "Google", "Facebook", "Tesla", "Twitter"]

        for companyName in defaultCompanies {
            let company = NSManagedObject(entity: entity,insertInto: managedContext)
            company.setValue(companyName, forKey: "name")
            company.setValue(companyName, forKey: "logo")
            companies.append(company)
        }
        fetchStocks()
        do {
            try managedContext.save()
            userDefaults.set(false, forKey: "firstRun")
            vc.tableView.reloadData()
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您的代码无法使用。您正在执行以下操作:

  • 创建默认公司(添加5个NSManagedObject个实例)
  • 获取股票价值。
  • 创建新公司(添加另外5个NSManagedObject个实例)。

现在您有10个条目而不是5个。

我的建议:

  • 创建文件Localizable.strings以将公司符号映射到真实姓名

    "AAPL" = "Apple";
    "TSLA" = "Tesla";
    "TWTR" = "Twitter";
    "GOOG" = "Google";
    "FB" = "FaceBook";
    
  • 然后首先股票价值。

  • 在循环中,通过symbol从密钥NSLocalizedString(comment:)获取真实姓名,创建NSManagedObject实例并设置属性。

这使用异步方式加载数据并替换setDefaultCompanies() fetchStocks()(未经测试)

func setDefaultCompanies() {

    // Default 5 companies at launch - user can delete/add/edit

    let userDefaults = UserDefaults.standard
    let defaultValues = ["firstRun" : true]
    userDefaults.register(defaults: defaultValues)

    if userDefaults.bool(forKey: "firstRun") {
        let entity = NSEntityDescription.entity(forEntityName: "Company", in: managedContext)!

        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(%22AAPL%22%2C%22GOOG%22%2C%22TWTR%22%2C%22TSLA%22%2C%20%22FB%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!) // or display an alert view
            } 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 symbol = quote["symbol"].stringValue
                        let name = NSLocalizedString(symbol, comment:"")
                        let ask = quote["Ask"].stringValue
                        let company = NSManagedObject(entity: entity,insertInto: self.managedContext)
                        company.setValue(name, forKey: "name")
                        company.setValue(name, forKey: "logo")
                        company.setValue(ask, forKey: "stockPrice")
                        self.companies.append(company)
                    }
                    DispatchQueue.main.async {
                       do {
                           try self.managedContext.save()
                           self.vc.tableView.reloadData()
                           userDefaults.set(false, forKey: "firstRun")
                       } catch let error as NSError {
                           print("Could not save. \(error), \(error.userInfo)")
                       }
                   }
                }
            } else {
                print("The data couldn't be loaded") // or display an alert view
            }
        }
        task.resume()
    }
}

答案 1 :(得分:0)

您的细胞没有正确出列。仅当在表视图中滚动单元格但未出列以保留其内容时,才会出现此问题。