簡體   English   中英

Swift JSON保存問題

[英]Swift JSON Saving issue

使用主/詳細信息核心數據模板時,我遇到了一個奇怪的問題,但可以想象,這只是我頭疼。 解析包含約800個學生的JSON文件時,幾乎可以立即將這些項目添加到TableView中。 我遇到的問題是,當嘗試將它們保存到Core Data上下文時,應用程序似乎暫停了將近一分鍾。

@IBAction func loadStudents(sender: AnyObject) {

    var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    var context: NSManagedObjectContext = appDel.managedObjectContext!

    let urlPath = NSURL(string: "**URL REMOVED**")
    let sharedSession = NSURLSession.sharedSession()
    let task = sharedSession.dataTaskWithURL(urlPath!, completionHandler: { (data, response, downloadTaskError) -> Void in

        println("Download Complete")

        if (downloadTaskError != nil) {

            println("Download Error: \(downloadTaskError!.localizedDescription)")

        } else {

            var studentJSONParseError: NSError?
            var studentJSONData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &studentJSONParseError) as NSArray

            if (studentJSONParseError != nil) {

                println("JSON Parsing Error: \(studentJSONParseError!.localizedDescription)")

            } else {

                for var i = 0; i < studentJSONData.count; i++ {

                    var student = studentJSONData[i] as NSDictionary
                    println("\(i) \(student)")
                    var newStudent = NSEntityDescription.insertNewObjectForEntityForName("Student", inManagedObjectContext: context) as Student
                    newStudent.firstName = student["STUDENT_FIRSTNAME"] as NSString
                    newStudent.lastName = student["STUDENT_SURNAME"] as NSString
                    newStudent.usualName = student["STUDENT_USUAL"] as NSString
                    newStudent.grade = student["STUDENT_GRADE"] as NSNumber
                    newStudent.id = student["STUDENT_ID"] as NSString
                    context.save(nil)

                }
            }
        }
    })

    task.resume()

}

首先,您要進行800次保存。 嘗試在循環之外進行操作,或者甚至更好地應用它們。 每400條記錄2次。

其次,您的核心數據保存在另一個線程上進行。 考慮保存在獲取結果控制器所在的主線程上。 后台線程有利於保存大量數據,在這里似乎並非如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM