【问题标题】:My fetchRequest return datas that are not in my database, why?我的 fetch 请求返回的数据不在我的数据库中,为什么?
【发布时间】:2015-08-03 12:28:48
【问题描述】:

我想从服务器获取对象“新闻”,存储它们,并在 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
}

【问题讨论】:

  • 也许你运行了两次程序?每次调用 insertNewObjectForEntityForName() 都会创建一个 new 对象。
  • 是的,但我每次都删除 sql 文件。我已经解决了这个问题,但我根本不明白...我用 managedObjectContext.save() 替换了所有循环,它可以工作.. ?!

标签: ios swift sqlite core-data


【解决方案1】:

也许您触发了两次请求?你永远不会删除条目 newsListOfAlamofire 或重新分配变量。

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 2021-05-31
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2019-01-18
    相关资源
    最近更新 更多