swift – JSON到NSManagedObject

我有一个JSON数据,当我第一次启动加载我的tableview时,我想映射到CoreData。 我在cellForRowAtIndexPath中find了一种方法,但是这种方式只能在显示单元格时将数据保存到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的build议。 但我得到“'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() } } 

我强烈build议把这个工作从cellForRowAtIndexpath中取出来,并做一个独立的函数,它将遍历你的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. } } 

你应该parsing你在responseJSON中收到的json:

 let jsonObj = NSJSONSerialization.JSONObjectWithData(json, options:NSJSONReadingOptions(rawValue: 0), error: &err) as! NSDictionary callback(jsonObj as! Dictionary<String, AnyObject>, nil) var recs:NSArray = jsonObj.objectForKey("authors") as! NSArray var ct:Int = 0 for item in recs{ var dict:NSDictionary = item as! NSDictionary // use self.yazarMakaleListesi[ct] here // process into the dict "author_name" , "author_id", etc // increment ct } self.tableView.reloadData()