在我的Swift 4代码中调用setValuesForKeys失败

时间:2017-11-16 22:27:30

标签: ios swift firebase swift4 nskeyvaluecoding

我遇到了这个问题,我试图从firebase数据库中检索数据,但是它说的是profilepic不是密钥,但确实如此。这是对象类。

class User: NSObject {
    var firstname: String?
    var lastname: String?
    var username: String?
    var profilepic: String?
}

这是我试图检索

func getusers(){
        ref.child("Friends").child(currentuser!).observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            if let dic = snapshot.value as? [String: AnyObject]{
                let user = User()
                user.setValuesForKeys(dic)
                print(user.firstname, user.lastname)

                DispatchQueue.main.async {
                    self.tableview.reloadData()
                }}
        }) { (error) in
            print(error.localizedDescription)
        }

    }

并且崩溃在user.setValuesForKeys(dic)

任何人都知道为什么不工作?

2 个答案:

答案 0 :(得分:2)

请改为尝试:

In [23]: lst = [l for l in raw['hits']['hits'] if l['_source'].get('authors')]

In [24]: json_normalize(lst, 
                        [['_source', 'authors']], 
                        ['_id', ['_source', 'journal'], ['_source', 'title']])
Out[24]:
           affiliations author_id          author_name       _id                                    _source.journal  \
0  [Punjabi University]  780E3459          munish puri  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
1  [Punjabi University]  48D92C79      rajesh dhaliwal  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
2  [Punjabi University]  7D9BD37C            r s singh  7AF8EBC3  Journal of Industrial Microbiology & Biotechno...
3                   NaN  7FF872BC  barbara eileen ryan  7521A721                     The American Historical Review
4                   NaN  0299B8E9     fraser j harbutt  7DAEB9A4                     The American Historical Review
5                   NaN  7DAB7B72   richard m freeland  7B3236C5                     The American Historical Review

                                       _source.title
0  Development of a stable continuous flow immobi...
1  Development of a stable continuous flow immobi...
2  Development of a stable continuous flow immobi...
3  Feminism and the women's movement : dynamics o...
4  The iron curtain : Churchill, America, and the...
5  The Truman Doctrine and the origins of McCarth...

@objcMembers class User: NSObject { ... } API由Foundation框架实现,需要Objective-C兼容性。

Swift 4中将Swift代码暴露给Objective-C的规则发生了很大变化。请check the evolution proposal获取更多信息。

用户类设计。如果Firebase中缺少四个属性中的任何一个,那么您的类设计可能非常适合。否则,请考虑将固定属性声明为非可选属性,并改为创建初始化程序。

答案 1 :(得分:1)

将您的用户声明更改为:

class User: NSObject {
    @objc var firstname: String?
    @objc var lastname: String?
    @objc var username: String?
    @objc var profilepic: String?
}

在Swift 4中,除非您明确公开它们,否则Objective-C无法看到您的实例属性。