我的fetchRequest返回不在我的数据库中的数据,为什么?

时间:2015-08-03 12:28:49

标签: ios swift sqlite core-data

我想获得对象"新闻"从服务器,存储它们,并在UITableView中显示它们。我成功使用HTTP请求(使用Alamofire),使用我的POJO进行映射(使用ObjectMapper),但是我对CoreData部分有一些麻烦......

我的问题是我在表格中存储了20行" NEWS",但是当我获取所有新闻时,我有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
}

1 个答案:

答案 0 :(得分:0)

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