我正在嘗試設置一個UITableView,其中包含實體中的所有對象。swift,從核心數據中刪除對象,仍然追加空對象?
但是,我正在從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數據嗎?也許你正在得到空物體。 – Nick
是的,它打印出來很好。 Tom Harrington在他的回答中找到了這個問題。 –