【问题标题】:Can not cast value of type NSTaggedPointerString to NSDictionary不能将 NSTaggedPointerString 类型的值转换为 NSDictionary
【发布时间】:2016-11-07 16:42:56
【问题描述】:

我正在尝试将 Firebase 值分配给我的结构:var productsArray = [Product]() 但是我有一个小错误:

无法将“NSTaggedPointerString”类型的值转换为 '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]
    }
}

在谷歌搜索时,我找不到任何解决方案。

【问题讨论】:

  • 错误信息是解决方案:NSTaggedPointerStringNSString,因此snapshot.value! 是字符串而不是字典。
  • snapshot.value 返回什么?你检查过 print snapshot.value???
  • @macmoonshine 这就是为什么我要转换它。@El Captain v2.0,它在附加var productsArray = [Product]() 时打印快照,但一旦它尝试分配值,它就会崩溃。
  • @EICaptainv2.0 我编辑了。
  • @TarvoMäesepp 以及该行为self.snusProductTitle = (snapshot.value! as! NSDictionary)["Products"] as! String 的函数 .. 也添加

标签: swift firebase


【解决方案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)
    }

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 2017-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    相关资源
    最近更新 更多