2017-06-23 90 views
0

首先有一個基類被稱爲BaseModel陣列,下面是代碼:如何獲得元件類型中迅速

class BaseModel : NSObject 
{ 
    var code:Int?   
    var message:Any? 

    public func setDictionaryToAttributes(dictionary_is dictionary:Dictionary<String,Any>?)->Bool 
    { 
     guard let dic:Dictionary<String,Any> = dictionary else {return false} 

     for (key,value) in dic { 
      let someType = type(of: value) 
      debugPrint("\(String(describing: someType.self))") 
      debugPrint("\(String(describing: someType))") 
      if someType is Array<Any>.Type { //i can't get TestListItemModel string    
       debugPrint("\(String(describing: someType))") 
      } 
     } 

     self.setValuesForKeys(dic) 
     return true; 
    } 
}//class BaseModel end 

並且存在從BaseModel

class TestListModel: BaseModel { 
    var tatalink:Any? 
    var items:Array<TestListItemModel>? 

    func setValuesFrom(jsonData j:JSON) { //j is a swifyJson object 

     guard var dic = j.dictionaryObject else {return} 
     if self.setDictionaryToAttributes(dictionary_is: dic)==false { 
      return 
     } 
    } 
} 
繼承另一個類

TestListModel中有子類的TestListItemModel類

class TestListItemModel:BaseModel { 
    var imgurl:  Any? 
    var title:  Any? 
} 

問題是: 我想從json數據自動解析BaseModel類中的所有屬性值。 in func analysetDictionaryToAttributes:我可以找到哪一個是Array,但我不知道如何獲取此類型並繼續調用它的analysetDictionaryToAttributes func。

+0

聲明你的字符串爲任何對象。 – KKRocks

+0

好吧,我會爲任何對象做到這一點,但我仍然無法得到xxxType陣列 xuanwenchao

+0

@KKRocks真誠地感謝您的回答,我在網上搜索了很長時間。但沒用。請幫助或嘗試提供一些想法如何實現這一點。 – xuanwenchao

回答

0

爲什麼你期望在你的BaseModel類函數中得到TestListItemModel。首先我看不到有TestListItemModel的任何結構。因爲我可以看到你只是過客JSON字典對象你爲什麼想到父類會知道這裏它的子類是TestListItemModelTestListModel它不知道你的類「TestListItemModel」在這一行

self.setDictionaryToAttributes(dictionary_is: dic) 

然後。因此,在這個功能

public func setDictionaryToAttributes(dictionary_is dictionary:Dictionary<String,Any>?)->Bool

你總是會得到字符串的字典作爲鍵和值作爲任何類型。如果你期待字符串,那麼你可以隨時檢查它這種方式

if value = value as String 
{ 
    print(value) 
} 
+0

謝謝你的回答,字典裏有多個KEY和VALUE,就像這樣:(「code」:「1」)(「message」:「xxx」)(「tatalink」:「xxx」) (「items」:「[xxx,xxx,xxx]」),我希望只有一個函數可以解析BaseModel中的所有屬性。 – xuanwenchao

+0

但是,如果還有其他childModel,baseModel永遠不會知道。如果你想解析它在childModels ..你可以用通用的方式解析它,例如[String:Any] .. –

+0

YES,我的困難是總是告訴我在BaseModel中輸入的是Array ,但我一直認爲我們可以在運行時間知道它,鏈接動態綁定原理。 – xuanwenchao