ios - 使用新数据快速更新 UITableView

标签 ios uitableview swift core-data

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

但是我当前的设置似乎不起作用,虽然在 SO 上有很多相同的问题,但我已经尝试过我能找到的答案。

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

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

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

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

  • 我设置了 managedObjectContext

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

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

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

  • 然后我进行第二次 API 调用(取决于第一个 API 的变量),获取该数据并以相同方式保存。

  • 我将对象追加到数组中,UITableView 从中填充它的单元格。 (我检查过它也能正确打印出来)

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

函数如下:

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 定义为我类的第一件事:

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

我认为这就是可能导致错误的所有代码。同样,我认为最有可能的原因是 loadSuggestions 函数。

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

任何关于找出为什么这个 tableView 拒绝更新的建议都会有很大的帮助!

对于代码墙,我深表歉意,但我无法找到问题的确切根源。

最佳答案

platinumFormulaTapGesture 函数中的这一行不正确,

SuggestionsViewController().loadSuggestions()

这会创建一个新的 SuggestionsViewController 实例,它不是您在屏幕上看到的实例。你需要得到一个指向你拥有的那个的指针。你如何做到这一点取决于你的 Controller 层次结构,你没有充分解释。

关于ios - 使用新数据快速更新 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29660543/

相关文章:

ios - 将自定义 tableviewcell 连接到 Uitableview

ios - 将 sqlite3_exec 回调函数的结果保存到 Swift 中的字典中

ios - 如何使用 Objective-c 实现 AES PKCS5Padding

ios - UITableView 单元格分隔符在被选中时消失

arrays - 按值对多维关联数组进行排序 (SWIFT)

swift - 在 Swift 3 和 Xcode 中使用堆栈 View 按钮打开 Storyboard View

ios - NSXMLParser - 空值

ios - 非法配置错误xcode6,我可以禁用它吗?

ios - swift : Save & Show selected indexPath in static Table View

ios - 如何停止 View Controller 以获取 tableView 单元格 subview 的触摸?