swift,从核心数据中删除对象,仍然附加空对象?

时间:2015-04-14 16:12:05

标签: ios uitableview swift core-data

我正在尝试设置一个UITableView,其中包含实体中的所有对象。

但是,我正在从api加载数据。所以每次加载时,我都会删除实体中的所有对象。并添加新的。

然而,当我这样做的时候。它显示了带有api数据的5个单元格,每次加载它时。它增加了5个空单元格。

它添加空单元格的原因是因为我定义的numberOfRowsInSection对象计数如下:

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

股票是:var stocks = [NSManagedObject]()

因此,我认为这是因为我的实体中有某些空对象?

这是我试图设置数据的方式:

    func loadSuggestions(Formula: Int) {
    println("----- Loading Data -----")
    // Check for an internet connection
    if Reachability.isConnectedToNetwork() == false {
        println("ERROR: -> No Internet Connection <-")
    } else {

        // Delete all the current objects in the entity
        let fetchRequest = NSFetchRequest(entityName: formulaEntity)
        let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject]
        for mo in a {
            managedContext.deleteObject(mo)
            //println("removed \(mo)")
        }
        // save the context after removing objects.
        managedContext.save(nil)

        // Setting up a fetch request to get 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!)

        for (index: String, actionable: JSON) in formula["actionable"] {
            stockName = actionable["name"].stringValue
            ticker = actionable["ticker"].stringValue
            action = actionable["action"].stringValue
            suggestedPrice = actionable["suggested_price"].floatValue
            weight = actionable["percentage_weight"].floatValue

            // Set the values in CoreData
            let stock = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext)

            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")

            // Set up second api fetch
            var quoteAPI = NSURL(string: "http://dev.markitondemand.com/Api/v2/Quote/json?symbol=\(ticker)")

            var quoteRequest = NSURLRequest(URL: quoteAPI!)
            var quoteData = NSURLConnection.sendSynchronousRequest(quoteRequest, returningResponse: nil, error: nil)
            if quoteData != nil {
                var quote = JSON(data: quoteData!)
                betterStockName = quote["Name"].stringValue
                lastPrice = quote["LastPrice"].floatValue

                // Setting the last values in CoreData
                if betterStockName != "" {
                    stock.setValue(betterStockName, forKey: "name")
                }
                stock.setValue(lastPrice, forKey: "lastPrice")

            } else {
                println("ERROR - NO DATA")
            }

            var error: NSError?
            if !managedContext.save(&error) {
                println("Could not save \(error), \(error?.userInfo)")
            }
            // finally add the stockdata to the CoreData entity.
            stocks.append(stock)


        }



        // Reload the tableview with the new data.
        self.tableView.reloadData()
    }
}

关于如何删除实体中的所有对象的信息不多。但是我试图打印出它正在删除的对象,而这一切似乎都是正确的。

但我必须在上述功能的某处做错事。因为每次调用上述函数时它会增加5个单元格。

任何帮助确定5个空单元格的来源以及如何修复它将非常感谢!

1 个答案:

答案 0 :(得分:1)

简单的原因是你只需要向stocks添加新条目,你永远不会删除任何内容。如果你从不从数组中删除任何东西,它将永远不会变小。

您确实从Core Data中删除了对象,但这并不会自动从阵列中删除它们。它们不会因为Core Data不再拥有它而从内存和数组中消失。在从Core Data中删除对象后,您需要通过调用阵列上的removeAll单独执行此操作。