只有JSON中的最后一项保存在Core Data中

时间:2016-03-07 14:30:56

标签: ios json swift core-data

我有一个调用远程PHP文件的函数。此文件以JSON格式返回数据。我可以看到应用程序收到完整的JSON数据。但是当我尝试将其保存到CoreData时,我认为JSON中的最后一条记录只能保存。请我的代码如下:

func get_territory(){
    deleteTerritory()
    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
    let managedObjectContext = appDelegate.managedObjectContext
    let entityDescription = NSEntityDescription.entityForName("Territory", inManagedObjectContext: managedObjectContext)
    let newCompany = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
    let defaults = NSUserDefaults.standardUserDefaults()
    let stringOne = defaults.stringForKey(defaultsKeys.staff_id)

    let mst_customer = defaults.stringForKey(defaultsKeys.mst_customer)
    let url = "http://xxxxxx.php?action=get_territory&mst_customer=" + mst_customer!
    print(url)
    let requestURL: NSURL = NSURL(string: url)!
    let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithRequest(urlRequest) {
        (data, response, error) -> Void in

        let httpResponse = response as! NSHTTPURLResponse
        let statusCode = httpResponse.statusCode

        if (statusCode == 200) {

            do{

                let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                print(json)
                if json is [AnyObject] {
                    // json starts with an array

                    for value in json as! [AnyObject]{
                        // loop through array
                        newCompany.setValue(value["id"], forKey: "orig_id")
                        newCompany.setValue(value["name"], forKey: "name")
                        //try managedObjectContext.save()
                    }

                } else if json is [String: AnyObject] {
                    // json starts with a key
                    print("2")
                } else {
                    // This json is broken
                    print("3")
                }

            }catch {
                print("Error with Json: \(error)")

            }

        }

    }

    task.resume()
}

当我注释掉try managedObjectContext.save()时,我在检索值时会收到Data:Fault。这是我从coredata中检索时使用的代码:

 var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
        var context:NSManagedObjectContext = appDel.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName:"Company")
        let fetchRequestTerritory = NSFetchRequest(entityName:"Territory")
        let fetchRequestFacility = NSFetchRequest(entityName:"Facility")
        let fetchRequestSpecialty = NSFetchRequest(entityName:"Specialty")
        let error:NSError
        do {
            let company_temp = try context.executeFetchRequest(fetchRequest)
            company = company_temp.flatMap{ $0 as? String }
            print(company_temp)

            let territory_temp = try context.executeFetchRequest(fetchRequestTerritory)
            territory = territory_temp.flatMap{ $0 as? String }
            print(territory_temp)

            let facility_temp = try context.executeFetchRequest(fetchRequestFacility)
            facility = facility_temp.flatMap{ $0 as? String }
            print(facility_temp)

            let specialty_temp = try context.executeFetchRequest(fetchRequestSpecialty)
            specialty = specialty_temp.flatMap{ $0 as? String }
            print(specialty_temp)

        } catch let error as NSError {
            // failure
            print("Fetch failed: \(error.localizedDescription)")
        }

0 个答案:

没有答案