我想把我的PlaceWorks从服务器添加到coredata
这是我的coredata对象

private var user: [User]?
private var myPlaceOfWorks: [MyPlaceOfWorks]?
private var context = sharedManagedObjectContext()

我试过这个
参数的工作区已成为类。
这个类控制json中的数组
func addInfo(workplace: [Sub_JsonModel_MyPlaceOfWorks], rtnvalue: String) ->
(User?, MyPlaceOfWorks?) {

    guard let newUser: User =
NSEntityDescription.insertNewObjectForEntityForName("User",
inManagedObjectContext: self.context) as? User else{
        return (nil, nil)

    }

    guard let newWorkPlace: MyPlaceOfWorks =
NSEntityDescription.insertNewObjectForEntityForName("MyPlaceOfWorks",
inManagedObjectContext: self.context) as? MyPlaceOfWorks else {
        return (nil, nil)
    }

    newUser.rtnvalue = rtnvalue

    for one in workplace {

        newWorkPlace.activeyn = one.ActiveYN
        newWorkPlace.basic = one.Basic
        newWorkPlace.beacon = one.Beacon
        newWorkPlace.cpiseq = one.CPISEQ
        newWorkPlace.cpmpoweq = one.CPMPOWSEQ
        newWorkPlace.companyname = one.CompanyName
        newWorkPlace.etime = one.ETime
        newWorkPlace.gps_latitude = one.GPS_latitude
        newWorkPlace.gps_longitude = one.GPS_longitude
        newWorkPlace.placename = one.PlaceName
        newWorkPlace.stime = one.STime
        newWorkPlace.wifi = one.Wifi
        self.myPlaceOfWorks?.append(newWorkPlace)
        print("newWorkPlace \(newWorkPlace)")
        print("myPlaceOfWorks \(myPlaceOfWorks)")
    }

    self.saveContext {
        //action
        print("newUser:: \(newUser)")

    }
    return (newUser, newWorkPlace)
}

private func saveContext(completion: (() -> Void)?) {
    do {
        try self.context.save()
        if let handler = completion {
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                handler()
            })
        }
    } catch let error {
        print("can not save context \(error)")
    }
}

我可以得到rtnvalue,但是,我不能得到myPlaceOfWorks数组对象!
只是没有
我怎么能试试这个?

最佳答案

您只创建了一个MyPlaceOfWorks类的对象,然后在循环中重写该对象的属性。相反,您需要在每个循环迭代中创建新实例。

for one in workplace {
    if let newWorkPlace: MyPlaceOfWorks = NSEntityDescription.insertNewObjectForEntityForName("MyPlaceOfWorks", inManagedObjectContext: self.context) as? MyPlaceOfWorks {
        newWorkPlace.activeyn = one.ActiveYN
        newWorkPlace.basic = one.Basic
        newWorkPlace.beacon = one.Beacon
        newWorkPlace.cpiseq = one.CPISEQ
        newWorkPlace.cpmpoweq = one.CPMPOWSEQ
        newWorkPlace.companyname = one.CompanyName
        newWorkPlace.etime = one.ETime
        newWorkPlace.gps_latitude = one.GPS_latitude
        newWorkPlace.gps_longitude = one.GPS_longitude
        newWorkPlace.placename = one.PlaceName
        newWorkPlace.stime = one.STime
        newWorkPlace.wifi = one.Wifi
        self.myPlaceOfWorks?.append(newWorkPlace)
    }
}
self.saveContext {
    //action
    print("newUser:: \(newUser)")

}

正如zcui93在注释中提到的,您需要实例化myPlaceOfWorks变量:
private var myPlaceOfWorks = [MyPlaceOfWorks]()

10-08 12:18