magicalpanda/MagicalRecord

Model.mapping(map: Map(mappingType: .fromJSON, JSON: meetingJson)) not saving ID

addame2 opened this issue · 0 comments

params- mapping before != nil Optional(3134620)
params- mapping after Optional(3134620) nil
params- saveInContext(meetingJson: Optional(3134620)
params- meetingFind 0 why my id is nil ? any idea?

    public static func saveInContext(meetingJson: [String : Any], source: MeetingSource, completion: ((MeetingModel?) -> Void)? = nil) {
        
        MagicalRecord.save { context in
            context.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.overwriteMergePolicyType)
            let ctx = MapManagedObjectContext(context: context)
            var meeting = MeetingModel.mr_findFirst(with: NSPredicate(format: "id=%@", meetingJson["id"] as! CVarArg), in: ctx.ctx)
            if meeting != nil {
                print("params- mapping before != nil", meeting?.id )
                meeting?.mapping(map: Map(mappingType: .fromJSON, JSON: meetingJson))
                print("params- mapping after", meeting?.id, meetingRes?.id )
            } else {
                print("params- mapping before == nil", meeting?.id )
                meeting = Mapper<MeetingModel>(context: ctx).map(JSON: meetingJson)
                print("params- mapping before == nil", meeting?.id)
            }
            meeting?.source = Int16(source.rawValue)
            
            if let profJson = meetingJson["prof"] as? [String : Any] {
                if let login = profJson["login"] as? String {
                    let profile = OtherUserModel.mr_findFirst(with: NSPredicate(format: "login = %@", login), in: ctx.ctx)
                    if profile != nil {
                        profile!.mapping(map: Map(mappingType: .fromJSON, JSON: profJson))
                        meeting?.prof = profile
                    } else {
                        let profile = Mapper<OtherUserModel>(context: ctx).map(JSON: profJson)
                        meeting?.prof = profile
                    }
                }
            }
            print("params- saveInContext(meetingJson:", meeting?.id )
            
            if let meetingFind = MeetingModel.mr_findFirst(with: NSPredicate(format: "source == \(MeetingSource.my.rawValue)")) {
                print("params- meetingFind", meetingFind.id )
            }
            
        } completion: { result, error in
            completion?(getMyMeeting())
        }
        
    }


    public static func getMyMeeting() -> MeetingModel? {
        if let meeting = MeetingModel.mr_findFirst(with: NSPredicate(format: "source == \(MeetingSource.my.rawValue)")) {
            return meeting
        }
        return nil
    }