ios - swift - JSON 到 NSManagedObject

标签 ios json swift core-data tableview

我有一个 JSON 数据,当我的 TableView 在第一次启动时加载时,我想将其映射到 CoreData。 我在 cellForRowAtIndexPath 中找到了一种方法,但是这样我只能在显示单元格时将数据保存到 CoreData 中。 我想对所有单元格执行一次。

    var yazarMakaleListesi: [JSON]? = []
    var authorList = [AuthorList]() // My CoreData

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCellWithIdentifier("YazarCell") as! YazarTableViewCell     
        cell.yazar = self.yazarMakaleListesi?[indexPath.row]

        cell.yazar = self.yazarMakaleListesi?[indexPath.row]
        let authorName = self.yazarMakaleListesi?[indexPath.row]["author_name"].string
        let authorID = self.yazarMakaleListesi?[indexPath.row]["author_id"].int
        let authorImage = self.yazarMakaleListesi?[indexPath.row]["author_image"].string
        let newspaperID = self.yazarMakaleListesi?[indexPath.row]["newspaper_id"].string
        let newspaperName = self.yazarMakaleListesi?[indexPath.row]["newspaper"].string
        let newsPaperImage = self.yazarMakaleListesi?[indexPath.row]["author_image"].string

        let articleEntity = NSEntityDescription.entityForName("AuthorList", inManagedObjectContext: self.context!)
        let newAuthor = AuthorList(entity: articleEntity!, insertIntoManagedObjectContext: self.context!)

        newAuthor.authorName = authorName!
        newAuthor.authorImage = authorImage!
        newAuthor.newspaperName = newspaperName!
        newAuthor.newsPaperImage = newsPaperImage!
        newAuthor.authorID = authorID!

        var saveError: NSError?
        self.context!.save(&saveError)

        if let _error = saveError {
            println("\(_error.localizedDescription)")
        } else {
            println("Author Saved!")
        }

        var error: NSError?
        let request = NSFetchRequest(entityName: "AuthorList")
        let results = self.context!.executeFetchRequest(request, error: &error) as! [AuthorList]

    return cell
    }

我在这里获取 JSON 数据:

   func loadYazar(){ 
        if (gazeteid != nil){
            let url = "http:myapi.com" + String(gazeteid)
            Alamofire.request(.GET, url).responseJSON { (Request, response, json, error) -> Void in
                if (json != nil){
                    var jsonObj = JSON(json!)
                    if let data = jsonObj["authors"].arrayValue as [JSON]?{
                        self.yazarMakaleListesi = data
                        self.tableView.reloadData()
                    }
                }
            }
        }
   }

编辑:我在这里得到我的 jsonresponse,实现了 @ thefredelement 的建议。 但我从以下行得到“'JSON'没有名为'valueForKey'的成员”:

newFakeCoreDataObject.authorName = jsonResult.valueForKey("authorName") as!字符串

Alamofire.request(.GET, url).responseJSON { (Request, response, json, error) -> Void in
    if (json != nil){
        var jsonObj = JSON(json!)
        if let jsonResults = jsonObj["authors"].arrayValue as [JSON]?{
            self.yazarMakaleListesi = jsonResults
            var error : NSError?
            for jsonResult in jsonResults {
                let newFakeCoreDataObject = FakeCoreDataObject()
                newFakeCoreDataObject.authorName = jsonResult.valueForKey("authorName") as! String
                self.context!.save(&error)                          
            }                 
                self.tableView.reloadData()
        }
    }   

最佳答案

我强烈建议将该工作从 cellForRowAtIndex 路径中取出,并创建一个单独的函数,该函数将迭代 JSON 结果并保存它们,然后从核心数据加载数据作为自定义对象,并将该对象放入实例数组中,然后使用该数组作为表数据。

编辑:我显然不会完全使用这段代码,这只是我试图解释的一个例子。

import UIKit
import CoreData

class FakeCoreDataObject : NSObject {

// this would really be your NSManagedObject subclass
var authorName = ""
var authorImage = NSData()
var newspaperName = ""
var newspaperImage = NSData()
var authorId = 0 as NSNumber

}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var myEntries = [FakeCoreDataObject]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    fetchJson()
    prepareTableData()
}

func fetchJson() {

    let appDel  = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext!

    var error : NSError?

    // Get your json reuslts like you are already
    var jsonResults = [AnyObject]() // just for an example

    for jsonResult in jsonResults {

        let newFakeCoreDataObject = FakeCoreDataObject()
        newFakeCoreDataObject.authorName = jsonResult.valueForKey("authorName") as! String
        // etc

        context.save(&error)
        // save whatever else you want for other entities, etc, if you need track out of scope you can do that and then save after the loop

    }
}

func prepareTableData() {

    let appDel  = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext!

    var error : NSError?

    let fetchTableDataRequest = NSFetchRequest(entityName: "whateverItIsCalled")
    fetchTableDataRequest.returnsObjectsAsFaults = false

    myEntries = context.executeFetchRequest(fetchTableDataRequest, error: &error) as! [FakeCoreDataObject]

    // If you need to do this often, reload the table data here too and you can call it from notifications, etc.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return myEntries.count
}


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // cell stuff you already have but just use the array
    // just a tip to set set values to "" or nil if you're creating a big table so you don't get duplciate data while scrolling
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

关于ios - swift - JSON 到 NSManagedObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31457363/

相关文章:

objective-c - UIScrollView 捏合手势识别器调用什么选择器?

android - JSON 对象解析错误

javascript - JSON 数组 javascript

ios - 如何打开 Instagram 查询方案以分享到故事?

arrays - 如何从 iOS 文件管理器获取文件名数组

ios - UITableView 的最后一个单元格在一段时间后自动消失?

ios - 如何让网站适配不同尺寸的手机屏幕?

ios - 我正在从网络服务调用图像的 url。图像未加载到 uitableview

php - 在 PHP 中搜索 MySQL 中的 JSON 数据

ios - 在 Swift 中读取 NSNotification userInfo