我正在尝试设置一个UITableView,其中包含一个实体中的所有对象。
但是,我正在从api中加载数据。所以每次加载时,我都会删除实体中的所有对象。加上新的。
但是当我这么做的时候。它显示了5个带有api数据的单元格,每次加载它。它增加了5个空细胞。
它添加空单元格的原因是,我定义的对象数如下所示:
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个空细胞,以及如何修复它将是非常感谢!
发布于 2015-04-14 09:29:37
原因很简单,因为您只向stocks
添加新条目,而从不删除任何内容。如果你从不从数组中删除任何东西,它就永远不会变小。
您确实从Core数据中删除了对象,但这并不会自动从数组中删除它们。它们不会仅仅因为Core数据不再拥有它们而从内存和数组中消失。在从Core中删除对象之后,您需要单独调用数组上的removeAll
。
https://stackoverflow.com/questions/29632319
复制