2014-09-02 3 views
1

빠른 클래스의 속성 목록을 가져 오려고합니다. 비슷한 질문이 herehere입니다. 어떤 타입을 제외하고는 모든 것이 작동합니다. class_copyPropertyList에서 반환되지 않습니다. 지금까지 테스트 한 것들은 Int?과 enums입니다. 나는 아래에있는 예제 클래스를 가지고있다.Swift 클래스의 속성 목록 가져 오기

enum PKApiErrorCode: Int { 
    case None = 0 
    case InvalidSignature = 1 
    case MissingRequired = 2 
    case NotLoggedIn = 3 
    case InvalidApiKey = 4 
    case InvalidLogin = 5 
    case RegisterFailed = 6 
} 

class ApiError: Serializable { 
    let code: PKApiErrorCode? 
    let message: String? 
    let userMessage: String? 

    init(error: JSONDictionary) { 
     code = error["errorCode"] >>> { (object: JSON) -> PKApiErrorCode? in 
      if let c = object >>> JSONInt { 
       return PKApiErrorCode.fromRaw(c) 
      } 

      return nil 
     } 

     message = error["message"] >>> JSONString 
     userMessage = error["userMessage"] >>> JSONString 
    } 
} 

그리고 https://gist.github.com/turowicz/e7746a9c035356f9483d에서 일부 도움으로 직렬화 클래스는합니다 (선택적 개체가 유효 값은 다음과 code이 개체에 표시되지 않을 경우가 열거 인 경우에만 나타납니다 것

public class Serializable: NSObject, Printable { 
    override public var description: String { 
     return "\(self.toDictionary())" 
    } 
} 

extension Serializable { 
    public func toDictionary() -> NSDictionary { 
     var aClass : AnyClass? = self.dynamicType 
     var propertiesCount : CUnsignedInt = 0 
     let propertiesInAClass : UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(aClass, &propertiesCount) 
     var propertiesDictionary : NSMutableDictionary = NSMutableDictionary() 
     for var i = 0; i < Int(propertiesCount); i++ { 

      var property = propertiesInAClass[i] 
      var propName = NSString(CString: property_getName(property), encoding: NSUTF8StringEncoding) 
      var propType = property_getAttributes(property) 
      var propValue : AnyObject! = self.valueForKey(propName); 
      if propValue is Serializable { 
       propertiesDictionary.setValue((propValue as Serializable).toDictionary(), forKey: propName) 
      } else if propValue is Array<Serializable> { 
       var subArray = Array<NSDictionary>() 
       for item in (propValue as Array<Serializable>) { 
        subArray.append(item.toDictionary()) 
       } 
       propertiesDictionary.setValue(subArray, forKey: propName) 
      } else if propValue is NSData { 
       propertiesDictionary.setValue((propValue as NSData).base64EncodedStringWithOptions(nil), forKey: propName) 
      } else if propValue is Bool { 
       propertiesDictionary.setValue((propValue as Bool).boolValue, forKey: propName) 
      } else if propValue is NSDate { 
       var date = propValue as NSDate 
       let dateFormatter = NSDateFormatter() 
       dateFormatter.dateFormat = "Z" 
       var dateString = NSString(format: "/Date(%.0f000%@)/", date.timeIntervalSince1970, dateFormatter.stringFromDate(date)) 
       propertiesDictionary.setValue(dateString, forKey: propName) 

      } else { 
       propertiesDictionary.setValue(propValue, forKey: propName) 
      } 
     } 

     return propertiesDictionary 
    } 

    public func toJSON() -> NSData! { 
     var dictionary = self.toDictionary() 
     var err: NSError? 
     return NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error: &err) 
    } 

    public func toJSONString() -> NSString! { 
     return NSString(data: self.toJSON(), encoding: NSUTF8StringEncoding) 
    } 
} 

문자열입니다 또는 Int Int가 기본값을 갖지 않는 한

어떤 조언을 해 주셔서 감사합니다. 클래스의 모든 속성을 얻는 데 도움이됩니다.

+0

어디서부터 시작해야하는지, 아니면 더 많은 정보가 필요한 사람이 있습니까? – smitt04

+0

동일한 요지를 사용하여 똑같은 문제가 발생했습니다. 에. 모든 업데이트? 나는 머리를 흔들어 계속해서 신속한 클래스를 직렬화하는 간단한 방법이 될 수 있다고 생각하지만, 아직 끝까지 작동하는 클래스를 찾지 못했습니다. –

답변

3

이 문제와 관련하여 Apple 개발자 포럼에서 답변을 얻었습니다 :

"class_copyPropertyList는 Objective-C 런타임에 노출 된 속성 만 표시합니다. 오브젝티브 C는 스위프트 열거 비 참조 타입의 선택적 항목을 나타낼 수 있으므로 이러한 특성은 대물-C 런타임에 노출되지 않는다. "

Source

따라서, 요약, 직렬화 JSON 이것을 사용 접근 방식은 현재 불가능합니다. 각 객체에 직렬화 작업을 제공하거나 객체를 JSON에 직렬화하기 위해 reflect() method을 사용하여 다른 패턴을 사용하여 조사해야 할 수 있습니다.

관련 문제