2016-07-04 6 views
2

alamofire를 사용하여 서버에서 응답 JSON을 얻은 다음 ObjectMapper를 사용하여 문자열을 Realm 객체에 매핑합니다.JSON 문자열이있는 Realm + Swift 업데이트 객체

The realm object is: 
    class SolutionVideo: Object, Mappable { 

dynamic var svID = 0 
dynamic var solutionTitle = "" 
dynamic var videoName = "" 
dynamic var relatedInfo = "" 
dynamic var shortDesc = "" 

override static func primaryKey() -> String? { 
    return "svID" 
} 

required convenience init?(_ map: Map) { 
    self.init() 
} 

func mapping(map: Map) { 
    svID <- map["svID"] 
    solutionTitle <- map["solutionTitle"] 
    videoName <- map["videoName"] 
    relatedInfo <- map["relatedInfo"] 
    shortDesc <- map["shortDescription"] 
} 

}

The json string is: 
    [ 
    { 
     "svID": "10", 
     "solutionTitle": "Video10", 
     "videoName": "Video10", 
     "realtedInfo": "", 
     "shortDescription": "" 
    }, 
    { 
     "svID": "9", 
     "solutionTitle": "Video9", 
     "videoName": "Video9", 
     "realtedInfo": "", 
     "shortDescription": "" 
    } 
    ] 



    in my viewController: 
     @IBAction func updateBtn(sender: AnyObject) { 
    // download file to update Realm 
    let url = "http://janicedemo.com/updates.json" 
    Alamofire.request(.GET, url).responseArray { (response: Response<[SolutionVideo], NSError>) in 
     let Array = response.result.value 
     print(Array) 
     if let Array = Array { 
      for video in Array { 
       let dbURL = Realm.Configuration.defaultConfiguration.fileURL 
       let realm = try! Realm(fileURL: dbURL!) 
       try! realm.write{ 
        print("will save") 
        realm.add(video, update: true) 
       } 
      } 
     } 
    } 

문제는 내가 성공적으로 개체를 추가 할 수 있다는 것입니다. 하지만 svID (primark 키)는 10이나 9 대신 JSON으로 0을 유지합니다. 내가 svID에 기본값을 설정했기 때문인가? 누군가 나에게 힌트를 줄 수 있습니까? 감사합니다

+0

이미 AlamofireObjectMapper 확장 프로그램을 사용하고 있습니까? – LNI

+0

예, 이미 사용했습니다 :) –

답변

1

class SolutionVideo: Object, Mappable { 

dynamic var svID = 0 
dynamic var solutionTitle = "" 
dynamic var videoName = "" 
dynamic var relatedInfo = "" 
dynamic var shortDesc = "" 

func setCompoundID(id: Int) { 
    self.svID = svID 
    compoundKey = compoundKeyValue() 
} 

func setCompoundID(id: Int) { 
    self.solutionTitle = solutionTitle 
    compoundKey = compoundKeyValue() 
} 

func setCompoundID(id: Int) { 
    self.videoName = videoName 
    compoundKey = compoundKeyValue() 
} 

func setCompoundID(id: Int) { 
    self.relatedInfo = relatedInfo 
    compoundKey = compoundKeyValue() 
} 

func setCompoundID(id: Int) { 
    self.shortDesc = shortDesc 
    compoundKey = compoundKeyValue() 
} 


dynamic lazy var compoundKey: String = self.compoundKeyValue() 

override static func primaryKey() -> String? { 
return “compoundKey” 
} 

func compoundKeyValue() -> String { 
    return "\(svID)\(solutionTitle)\(videoName)\(relatedInfo)\(shortDesc)” 
} 

} 
+0

AlamofireObjectMapper를 사용하고 있는데, alamofire와 objectmapper가 결합되어 있습니다. –

+0

내 업데이트를 참조하십시오. 그게 효과가 있니? 커스텀 setter를 사용하면 compoundKey가 항상 업데이트되도록합니다. lazy var은 처음 액세스 한 속성을 사용자가 설정 한 것으로부터 가져옵니다. – tymac

+0

그것은 옳지 않습니다. 맵핑을 시도 할 때 svID가 get-only 인 오류가 발생합니다. –

0

내가 생각할 수있는 중요한 것은이 기본 키 값이 대신 (즉, "10" 대신 단순히 10의) 적절한 정수의 문자열로 내려 오는 것을보십시오.

svID <- (map["svID"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) 
: 당신은 당신의 매핑 기능이 변환 인라인을 수행 할 수 있어야합니다, 그것은 매퍼가 정수로 문자열 변환을 처리 할 수있을만큼 똑똑하지 않다 가능성, 그래서 그냥 0

According to the ObjectMapper documentation을 디폴트 있어요

또한 sidenote로 JSON 키 이름 중 하나에 맞춤법 오류 : "realtedInfo"이 있음을 확인했습니다. 그래서 나는 더블 체크를하는 것이 좋습니다. :)

관련 문제