2016-11-07 64 views
2

我試圖火力地堡值分配給我的結構:var productsArray = [Product]()但是我有一個小錯誤:不能投射型NSTaggedPointerString的值的NSDictionary

Could not cast value of type 'NSTaggedPointerString' to 'NSDictionary'.

我知道,我不能直接給他們,使就是我爲什麼鑄造這樣的:

self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String 

並轉換:

func toAnyObject() -> [String: Any] { 

     return ["Products": snusProductTitle as Any] 
    } 

喜歡我追加:

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName) 
     ref.observeSingleEvent(of: .childAdded, with: { (posts) in 
      self.productsArray.removeAll() 
      var newPostsArray = [Product]() 
      for post in posts.children { 
       print(posts.value)//Look below image 
       let newPost = Product(snapshot: post as! FIRDataSnapshot) 
       newPostsArray.insert(newPost, at: 0) 
      } 

      self.productsArray = newPostsArray 
      self.tableView.reloadData() 

     }) { (error) in 
      print(error.localizedDescription) 
     } 

這是最小的產品結構:

class Product: NSObject { 
    var snusProductTitle: String! 


    var ref: FIRDatabaseReference? 

    init(snusProductTitle: String) { 
     self.snusProductTitle = snusProductTitle 
     self.ref = FIRDatabase.database().reference() 
    } 



    init(snapshot: FIRDataSnapshot){ 
     self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String 
    } 

    func toAnyObject() -> [String: Any] { 
     return ["Products": snusProductTitle as Any] 
    } 
} 

enter image description here

在谷歌上搜索,我無法找到任何解決方案。

+0

該錯誤消息是解決方案:'NSTaggedPointerString'是一個'NSString',從而''snapshot.value是一個字符串不是字典!。 – clemens

+0

'snapshot.value'返回什麼?你打印檢查'snapshot.value'? –

+0

@macmoonshine這就是爲什麼我將它轉換成tho .. @El Captain v2.0,它在追加'var productsArray = [Product]()'的同時打印快照,但只要它嘗試分配值,就會崩潰。 –

回答

1

.childAdded一次給出FIRDataSnapshot ...所以不需要爲此循環..你只需要在你的結構中傳遞當前的孩子。

self.productsArray.removeAll() 
var newPostsArray = [Product]() 

let ref = FIRDatabase.database().reference().child("Snuses").queryOrdered(byChild: "Brand").queryEqual(toValue: brandName) 
    ref.observe(FIRDataEventType.childAdded, with: { (posts) in 

     let newPost = Product(snapshot: posts as! FIRDataSnapshot) 
     newPostsArray.insert(newPost, at: 0) 

     self.productsArray = newPostsArray 
     self.tableView.reloadData() 

    }) { (error) in 
     print(error.localizedDescription) 
    } 
相關問題