我不知道任何特定的實現,但鍵值編碼讓你非常接近你想要的:Key Value Coding Guide。我已將streamed json parsing與KVC結合起來,取得了不錯的成績。
-setValue:forKey:方法使序列化數據適應自定義對象非常簡單。要繼續你的例子,你需要創建一個具有所有必需的訪問器方法的Unicorn類:-setName:/ - name,-setManeColor/-maneColor等等(你可以使用某些期望值的屬性,但有與maneColor值一樣,您可能希望編寫自定義setter以從顏色名稱字符串轉換爲NSColor或UIColor對象。)
您還需要將另外兩個方法添加到自定義對象:-setValue:forUndefinedKey:和-valueForUndefinedKey :.如果你的對象沒有匹配傳遞給KVC方法的鍵的訪問器方法,那麼這些方法將被調用。您可以在這裏捕獲意外或不支持的值,並根據需要存儲或忽略它們。
當您將-setValue:forKey:發送給Unicorn對象時,框架將查找與鍵模式匹配的訪問器。例如,如果鍵是「maneColor」,並且您正在設置該值,那麼框架將檢查您的對象是否實現了-setManeColor :.如果是這樣,它調用該方法,傳入值;否則,調用-setValue:forUndefinedKey:,如果對象沒有實現它,則拋出異常。
當解析器的委託收到解析json獨角獸對象的通知已經開始時,實例化一個Unicorn對象。當你的解析器返回的分析數據給你,用-setValue:forKey:將數據添加到您的對象:
- (void)parserDidBeginParsingDictionary: (SomeParser *)p
{
self.currentUnicorn = [ Unicorn unicorn ];
}
- (void)parser: (SomeParser *)p didParseString: (NSString *)string
forKey: (NSString *)key
{
[ self.currentUnicorn setValue: string forKey: key ]
}
- (void)parserDidFinishParsingDictionary: (SomeParser *)p
{
[ self.unicorns addObject: self.currentUnicorn ];
}
+1獨角獸 – psy 2012-05-04 16:32:21