2016-10-19 26 views
0

這並不完全是我無法解決這個問題,但是有適當和不正確的方法,我不想使用有缺陷的方法。我從火力此快照,我宣佈它的NSDictionary像這樣:什麼是從NSDictionaries獲取值以分離變量的正確方法

let commentDict = commentsDictionary.value as? NSDictionary 

當我打印commentDict它看起來像這樣:

commentText = Fififgkffy; 
    postedBy = USXhV0QYkpbSzAmXgfeteXHuoqg2; 
    commentText = Fhzifigh; 
    postedBy = USXhV0QYkpbSzAmXgfeteXHuoqg2; 

CommentDict總是這個樣子。它將始終有2個項目。我想知道獲取項目並將它們分配給變量的正確方法。我以前也使用過,但只是在一個項目中的一個方法是把這個在for循環中:

if name as! String == "postedBy" { 

然後我得到了「postedBy」字典項的值。當有2個項目時,我應該爲commentText和postingBY創建一個小數組,並且每個數組有兩個數組?另一個重要的觀點是這些必須留在他們自己的羣體中。我必須跟蹤哪個「commentText」是第一個組,哪個是第二個組,與「postingBy」相同。

從長遠來看,我不得不以commentText1,postingBy1,commentText2,postingBy2作爲單獨的字符串變量。

+0

它是否可以強制轉換爲NSDictionary數組? 'commentDict'的打印值aboce應該有'[]'我假設 – xmhafiz

+0

這樣做當你把firdatasnapshot或w/e轉換成nsdictionary時,我認爲它有點像2個單獨的字典或者我不知道它很奇怪 –

+0

你知道你能把它當作一本大字典來對待。當我在commentDict中使用for循環(name,value)時,我打印它的值,它打印所有的值,所以有4個值。我可以將所有4個字符串放到一個字符串數組中tbh我的意思是我沒有看到它們會如何失序。 –

回答

0

這就是我最終做的,但我只想知道是否有更好或更「適當」的方式來做到這一點。我可能必須將一些安全if語句放入此方法中,以確保數組得到正確填充和所有這些。

if let commentDict = commentsDictionary.value as? NSDictionary { 
    for(name, value) in commentDict { 
      commentInfoArray.append(value as! String) 
    } 
    let comment1Text = commentInfoArray[0] 
    let comment1User = commentInfoArray[1] 
    let comment2Text = commentInfoArray[2] 
    let comment2User = commentInfoArray[3] 
} 
0

如果只有postedBycommentText關係,即你正在使用這個作爲你的結構尋找嘗試: -

USXhV0QYkpbSzAmXgfeteXHuoqg2 : comment1 : true, 
            comment2 : true, 
    //postedById : [postText] 

然後在您的檢索使用字典將數據追加到: -

db_Ref.child(userID).observeSingleEvent(of: .value, with: {(snap) in 

     if let commentDict = snap.value as? [String:AnyObject]{ 

      for each in commentDict{ 

       print(each.key) // Append your key here 

      } 
     } 
    }) 
+0

你給它一個鏡頭? – Dravidian

相關問題