2016-07-12 7 views
1

私はこの設定がこのようなplistファイルを持っています。辞書と配列の組み合わせからswiftのplistからデータを取得する2.2

項目3自体がarrayあるITEM3

そのルートは、3項目、ITEM1、ITEM2を有するdictionaryです。

root_dictの値を取得すると、item3は値をarrayとして返します。

Item3の項目(item4)はdictionaryです。

var myDict: NSDictionary? 


    if let path = NSBundle.mainBundle().pathForResource("info", ofType: "plist") { 
     myDict = NSDictionary(contentsOfFile: path) //mydict has 3 item 
    } 

    var dicData = myDict!["item3"] as! Dictionary<String, AnyObject> 

    for (key, value) in dicData{ 

     print(key) 
    } 

そのが動作していない:項目4は、私は以下のコードを使用していますitem5

root_dict 
    item1 --- string 
    item2 --- dict 
    item3 --- array 
     | 
     ------ item 4 ---- dic 
       | 
       -------------item5----array 

の値を取得したい項目(item5)

を持っています。

どのようなヘルプも高く評価されます。

+0

あなたはこのようなコードを変更してくださいできませんディクショナリに辞書を変換しようとしています 'var dicData = myDict![" item3 "] as! [[String:AnyObject]] ' –

+0

私はurコードを使用すると、' NSDictionary '(0x7fff764d2aa0)に' __NSArrayM '(0x7fff764d25c8)型の値をキャストできませんでした。 – noor

+0

あなたのplistのルートオブジェクトのように見えるのは、配列 –

答えて

1

は最終的に私が欲しいanswer.Butを持って試してみるべきである

var myDict: NSDictionary? 


     if let path = NSBundle.mainBundle().pathForResource("fetchData", ofType: "plist") { 
      myDict = NSDictionary(contentsOfFile: path) //mydict has 3 item 
     } 

     var dicData = myDict!["item3"] as! NSArray 
     print(dicData.valueForKey("item5"))   

最初にコンセプトをクリアする。

1. first, root returns a dict key.One of the dict key is array. 
2. so, first from dict, i have to get that array. 
3. Again, array contains an dict item. so i have to convert the array to dict. 

私は必要なものとしてキーを渡す関数を使用します。私はこの機能を2〜3回使うことも、キーに基づいた私の願いとして使うこともできます。

//get the plist and get the root dict 
if let path = NSBundle.mainBundle().pathForResource("test", ofType: "plist") 
    { 
     myDict = NSDictionary(contentsOfFile: path) 
    } 

dictキーに基づいてループ2または3または4以上で以下の関数を使用するよりも、

2

私は@Nirav Doに完全に同意します。以下のように動作するかもしれません。あなたのコンソール出力が ( (ここで //あなたのデータ です) )

+0

ですが、実際には完全な項目4を返しますが、項目5の値のみを必要とします。 – noor

+0

item3は、項目4がdict項目である配列を返します。どのように返された配列からitem4 dict値を取得できますか? – noor

1

は、あなたがこの

var myDict: NSDictionary? 
if let path = NSBundle.mainBundle().pathForResource("info", ofType: "plist") { 
    myDict = NSDictionary(contentsOfFile: path) //mydict has 3 item 
} 
let dicData = myDict!["item3"] as! [[String : AnyObject]] // If this not work try this below statment 

//let dicData = myDict!["item3"] as! NSArray 

//Now get your dictionary object from array like this 

let dic = dicData.firstObject as! [String : AnyObject] 
let item5Array = dic["item5"] as! NSArray 
print(item5Array) // item5Array is array that you want.  
関連する問題