用新的数据Swift更新UITableView

我正在尝试用另一个JSON调用的数据重新填充我的UITableView

然而,我目前的设置似乎并没有工作,虽然有许多相同的问题,所以我可以find我已经尝试的答案。

我将我的API数据保存在CoreData实体对象中。 我用我的CoreData实体填充我的UITableView。

在我目前的设置中,我有3个不同的API调用,有不同数量的数据,当然还有不同的值。 我需要能够在这三个数据集之间切换,这就是我现在要完成的。 (到目前为止没有进展)。

我有一个名为“loadSuggestions”的函数,这是我的错误所在。

  • 首先我检查互联网连接。

  • 我设置了managedObjectContext

  • 我检查了我需要调用的API(这是在函数被调用之前确定的,我检查了它是否按预期工作)

  • 我从它试图调用的实体中删除所有当前数据。 (我也尝试从UITableView加载的最后一个数据中删除数据,这并没有改变任何东西)。 我也检查了这个工作。 删除数据后,我检查它打印出一个空数组,我也尝试logging它删除的对象,以确保。

  • 然后我获取新的数据,保存到临时variables。 然后将其保存到我的核心数据。

  • 然后,我做我的第二个API调用(取决于从第一个variables),获取该数据并以相同的方式保存。

  • 我将该对象追加到UITableView填充它的单元格的数组中。 (我检查它打印出来也是如此)

  • 最后我重新加载tableView。 (不改变事物)

这个function:

 func loadSuggestions() { println("----- Loading Data -----") // Check for an internet connection. if Reachability.isConnectedToNetwork() == false { println("ERROR: -> No Internet Connection <-") } else { // Set the managedContext again. managedContext = appDelegate.managedObjectContext! // Check what API to get the data from if Formula == 0 { formulaEntity = "TrialFormulaStock" println("Setting Entity: \(formulaEntity)") formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json") } else if Formula == 1 { formulaEntity = "ProFormulaStock" println("Setting Entity: \(formulaEntity)") formulaAPI = NSURL(string: "http://api.com/json/entry_weekly.json") } else if Formula == 2 { formulaEntity = "PremiumFormulaStock" formulaAPI = NSURL(string: "http://api.com/json/proff_weekly.json") println("Setting Entity: \(formulaEntity)") } else if Formula == 3 { formulaEntity = "PlatinumFormulaStock" println("Setting Entity: \(formulaEntity)") formulaAPI = NSURL(string: "http://api.com/json/fund_weekly.json") } // Delete all the current objects in the dataset let fetchRequest = NSFetchRequest(entityName: formulaEntity) let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject] for mo in a { managedContext.deleteObject(mo) } // Removing them from the array stocks.removeAll(keepCapacity: false) // Saving the now empty context. managedContext.save(nil) // Set up a fetch request for the API data let entity = NSEntityDescription.entityForName(formulaEntity, inManagedObjectContext:managedContext) var request = NSURLRequest(URL: formulaAPI!) var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil) var formula = JSON(data: data!) // Loop through the api data. for (index: String, actionable: JSON) in formula["actionable"] { // Save the data into temporary variables stockName = actionable["name"].stringValue ticker = actionable["ticker"].stringValue action = actionable["action"].stringValue suggestedPrice = actionable["suggested_price"].floatValue weight = actionable["percentage_weight"].floatValue // Set up CoreData for inserting a new object. let stock = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext) // Save the temporary variables into coreData stock.setValue(stockName, forKey: "name") stock.setValue(ticker, forKey: "ticker") stock.setValue(action, forKey: "action") stock.setValue(suggestedPrice, forKey: "suggestedPrice") stock.setValue(weight, forKey: "weight") // Get ready for second API call. var quoteAPI = NSURL(string: "http://dev.markitondemand.com/Api/v2/Quote/json?symbol=\(ticker)") // Second API fetch. var quoteRequest = NSURLRequest(URL: quoteAPI!) var quoteData = NSURLConnection.sendSynchronousRequest(quoteRequest, returningResponse: nil, error: nil) if quoteData != nil { // Save the data from second API call to temporary variables var quote = JSON(data: quoteData!) betterStockName = quote["Name"].stringValue lastPrice = quote["LastPrice"].floatValue // The second API call doesn't always find something, so checking if it exists is important. if betterStockName != "" { stock.setValue(betterStockName, forKey: "name") } // This can simply be set, because it will be 0 if not found. stock.setValue(lastPrice, forKey: "lastPrice") } else { println("ERROR ----------------- NO DATA for \(ticker) --------------") } // Error handling var error: NSError? if !managedContext.save(&error) { println("Could not save \(error), \(error?.userInfo)") } // Append the object to the array. Which fills the UITableView stocks.append(stock) } // Reload the tableview with the new data. self.tableView.reloadData() } } 

目前,当我推到这个viewController,这个函数在viewDidAppear调用,如下所示:

 override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) tableView.allowsSelection = true if isFirstTime { loadSuggestions() isFirstTime = false } } 

它填充tableView正确,一切似乎按计划工作。

但是,如果我打开我的滑出菜单,并调用一个函数来加载不同的数据,没有任何反应,这里是一个示例函数:

 func platinumFormulaTapGesture() { // Menu related actions selectView(platinumFormulaView) selectedMenuItem = 2 // Setting the data to load Formula = 3 // Sets the viewController. (this will mostly be the same ViewController) menuTabBarController.selectedIndex = 0 // Set the new title navigationController?.navigationBar.topItem!.title = "PLATINUM FORMULA" // And here I call the loadSuggestions function again. (this does run) SuggestionsViewController().loadSuggestions() } 

以下是2个相关的tableView函数:

行数:

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

和cellForRowAtIndexPath(这是我用CoreData设置我的单元格的地方)

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("com.mySuggestionsCell", forIndexPath: indexPath) as! mySuggestionsCell let formulaStock = stocks[indexPath.row] cell.stockNameLabel.text = formulaStock.valueForKey("name") as! String! cell.tickerLabel.text = formulaStock.valueForKey("ticker") as! String! action = formulaStock.valueForKey("action") as! String! suggestedPrice = formulaStock.valueForKey("suggestedPrice") as! Float let suggestedPriceString = "Suggested Price\n$\(suggestedPrice.roundTo(2))" as NSString var suggestedAttributedString = NSMutableAttributedString(string: suggestedPriceString as String) suggestedAttributedString.addAttributes(GrayLatoRegularAttribute, range: suggestedPriceString.rangeOfString("Suggested Price\n")) suggestedAttributedString.addAttributes(BlueHalisRBoldAttribute, range: suggestedPriceString.rangeOfString("$\(suggestedPrice.roundTo(2))")) cell.suggestedPriceLabel.attributedText = suggestedAttributedString if action == "SELL" { cell.suggestionContainer.backgroundColor = UIColor.formulaGreenColor() } if let lastPrice = formulaStock.valueForKey("lastPrice") as? Float { var lastPriceString = "Last Price\n$\(lastPrice.roundTo(2))" as NSString var lastAttributedString = NSMutableAttributedString(string: lastPriceString as String) lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n")) percentDifference = ((lastPrice/suggestedPrice)*100.00)-100 if percentDifference > 0 && action == "BUY" { lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))")) } else if percentDifference <= 0 && percentDifference > -100 && action == "BUY" { lastAttributedString.addAttributes(GreenHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))")) } else if percentDifference <= 0 && percentDifference > -100 && action == "SELL" { lastAttributedString.addAttributes(RedHalisRBoldAttribute, range: lastPriceString.rangeOfString("$\(lastPrice.roundTo(2))")) } else if percentDifference == -100 { lastPriceString = "Last Price\nN/A" as NSString lastAttributedString = NSMutableAttributedString(string: lastPriceString as String) lastAttributedString.addAttributes(GrayLatoRegularAttribute, range: lastPriceString.rangeOfString("Last Price\n")) lastAttributedString.addAttributes(BlackHalisRBoldAttribute, range: lastPriceString.rangeOfString("N/A")) } cell.lastPriceLabel.attributedText = lastAttributedString } else { println("lastPrice nil") } weight = formulaStock.valueForKey("weight") as! Float cell.circleChart.percentFill = weight let circleChartString = "\(weight.roundTo(2))%\nWEIGHT" as NSString var circleChartAttributedString = NSMutableAttributedString(string: circleChartString as String) circleChartAttributedString.addAttributes(BlueMediumHalisRBoldAttribute, range: circleChartString.rangeOfString("\(weight.roundTo(2))%\n")) circleChartAttributedString.addAttributes(BlackSmallHalisRBoldAttribute, range: circleChartString.rangeOfString("WEIGHT")) cell.circleChartLabel.attributedText = circleChartAttributedString cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } 

我把我的appDelegate定义为我class里的第一件事情:

 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate var managedContext = NSManagedObjectContext() 

我认为这就是所有可能导致错误的原因。 再次,我认为最有可能的原因是loadSuggestions函数。

为了强制更新tableView,我也尝试在self.viewtableView上调用setNeedsDisplaysetNeedsLayout这两者似乎都没有做任何事情。

任何build议,搞清楚为什么这tableView拒绝更新将是一个巨大的帮助!

我为代码的墙壁表示歉意,但我无法find问题的确切来源。

这个行在platinumFormulaTapGesture函数中是不正确的,

 SuggestionsViewController().loadSuggestions() 

这将创build一个ViewsViewController的新实例,这不是您在屏幕上显示的实例。 你需要得到一个指针,你有。 你如何做到这一点取决于你的控制器层次结构,你还没有完全解释。