Mark L
Mark L

Reputation: 759

swift, removing objects from core data, still appends empty objects?

I'm attempting to set up a UITableView, with all objects in an entity.

However, I'm loading the data from an api. So every time it loads, I'm deleting all the objects in the entity. And adding the new ones.

However, when I do this. It's showing 5 cells with the api data, and every time I load it. It adds 5 empty cells.

The reason it's adding empty cells is because I'm defining numberOfRowsInSection with objects count like so:

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

Where stocks is: var stocks = [NSManagedObject]()

So from that I assume it's because there's somehow empty objects in my entity?

here's how I'm trying to set up my data:

    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()
    }
}

There isn't a lot of information on how to delete all of the objects in an entity. But I tried to print out the objects it was deleting, and that all seemed correct.

But I must be doing something wrong somewhere in the above function. Since it adds 5 more cells every time the above function is called.

Any help figuring out where the 5 empty cells are coming from and how to fix it would be greatly appreciated!

Upvotes: 2

Views: 980

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70936

The simple reason is that you only ever add new entries to stocks, you never remove anything. If you never remove anything from the array, it will never get smaller.

You do delete the objects from Core Data, but that doesn't automatically remove them from the array. They don't disappear from memory and an array just because Core Data doesn't have them anymore. You need to do that separately by calling removeAll on the array after deleting the objects from Core Data.

Upvotes: 1

Related Questions