我想从服务器获取对象“新闻”,存储它们,并将它们显示在 UITableView 中。我成功地完成了 HTTP 请求(使用 Alamofire),使用 POJO 进行映射(使用 ObjectMapper),但是我在 CoreData 部分遇到了一些麻烦...
我的问题是我的表“NEWS”中存储了 20 行,但是当我获取所有新闻时,我有 40 行,实际上是 20 行实际行的两倍。 为什么?
class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var mTableView: UITableView!
let newsCellIdentifier = "NewsCell"
var dataStack: DATAStack?
var newsList = [News]()
var newsListOfAlamofire = [News]()
override func viewDidLoad() {
super.viewDidLoad()
self.dataStack = DATAStack(modelName: "UdAMobile2")
let url = "xxxxxxxxxx"
Alamofire.request(.GET, url, parameters: ["service" : "news"])
.responseArray { (response: [News]?, error: NSError?) in
if let response = response {
for oneNews in response {
self.newsListOfAlamofire.append(oneNews)
}
}
//self.saveNewsInDatabase()
self.getDatasFromBD()
self.mTableView.reloadData()
}
}
func saveNewsInDatabase() {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedObjectContext = appDelegate.managedObjectContext!
for news in newsListOfAlamofire {
var newsToSave = NSEntityDescription.insertNewObjectForEntityForName("News", inManagedObjectContext: managedObjectContext) as! News
newsToSave = news
var error : NSError? = nil
if !managedObjectContext.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
func getDatasFromBD() {
super.viewWillAppear(true)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext!
let sortDescriptor = NSSortDescriptor(key: "datePublication", ascending: false)
var sortDescriptorArray :NSArray = [sortDescriptor]
let fetchRequest = NSFetchRequest(entityName:"News")
fetchRequest.sortDescriptors = sortDescriptorArray as [AnyObject]
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [News]
if let results = fetchedResults {
newsList = results
println("Récupération de \(fetchedResults!.count) news depuis la base")
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.newsList.count;
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url = NSURL(string: self.newsList[indexPath.row].lien!)
UIApplication.sharedApplication().openURL(url!)
self.mTableView.deselectRowAtIndexPath(indexPath, animated: true)
}
//MARK - My Implementation
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return newsCellAtIndexPath(indexPath)
}
func newsCellAtIndexPath(indexPath:NSIndexPath) -> NewsCell {
let cell = self.mTableView.dequeueReusableCellWithIdentifier(newsCellIdentifier) as! NewsCell
setTextForCell(cell, indexPath: indexPath)
setImageForCell(cell, indexPath: indexPath)
return cell
}
func setTextForCell(cell:NewsCell, indexPath:NSIndexPath) {
let news = newsList[indexPath.row] as News
if var label = cell.mLabelRestaurantName {
label.text = news.titre
cell.mLabelPeriode.text = news.periode
}
}
func setImageForCell(cell :NewsCell, indexPath :NSIndexPath) {
var url = newsList[indexPath.row].urlImg
if url == nil {
url = ""
}
cell.mImageView.kf_setImageWithURL(NSURL(string: url!)!, placeholderImage: UIImage(named: "uda.png"))
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
最佳答案
也许您触发了两次请求?你永远不会删除条目
newsListOfAlamofire
或重新分配变量。
关于ios - 我的 fetchRequest 返回的数据不在我的数据库中,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31787286/