2016-09-11 1 views
0

지금까지 Alamofire를 사용하여 데이터를 다운로드 할 모델 클래스와 도우미 클래스가 있습니다. 내 질문은 어디에서 데이터를 구문 분석하고 모델의 개체에 할당해야합니까? 모델 자체 또는 도우미 클래스에서 수행해야합니까? 아니면 다른 곳에서 수행해야합니까? "최선의 방법"으로 간주되는 것을하려고합니다. 감사합니다.Swift에서 JSON을 구문 분석하는 모범 사례, OOP-wise

답변

1

클래스가 의미가 있다면, 클래스가 될 자격이 있습니다. 따라서 직렬화 및 구문 분석 클래스는 내 생각에 클래스가되어야합니다. 잘 어울린다.

슬프게도이 목적을 위해 작성한 프레임 워크가있어서 쉽게 처리 할 수 ​​있습니다. 예를 들어, "ObjectMapper"에는 "AlamofireObjectMapper"라는 확장명이 있습니다.

https://github.com/tristanhimmelman/AlamofireObjectMapper

그리고 당신과 같이 사용할 수 있습니다 :

let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json" 
Alamofire.request(.GET, URL).responseObject { (response: Response<WeatherResponse, NSError>) in 

    let weatherResponse = response.result.value 
    print(weatherResponse?.location) 

    if let threeDayForecast = weatherResponse?.threeDayForecast { 
     for forecast in threeDayForecast { 
      print(forecast.day) 
      print(forecast.temperature)   
     } 
    } 
} 
관련 문제