【问题标题】:swift, removing objects from core data, still appends empty objects?快速,从核心数据中删除对象,仍然附加空对象?
【发布时间】:2015-04-14 16:12:05
【问题描述】:

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

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

但是,当我这样做时。它显示了 5 个带有 api 数据的单元格,每次我加载它时。它添加了 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 个空单元格的来源以及如何修复它,将不胜感激!

【问题讨论】:

  • 您是否注销了返回的 JSON 数据?也许你得到的是空对象。
  • 是的,它打印得很好。 Tom Harrington 在下面的回答中发现了这个问题。

标签: ios uitableview swift core-data


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    相关资源
    最近更新 更多