在Swift中,对于AnyObject,我如何先setValue()然后调用valueForKey() [英] In Swift, for AnyObject, how do I setValue() then call valueForKey()

查看:60
本文介绍了在Swift中,对于AnyObject,我如何先setValue()然后调用valueForKey()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在AnyObject中存储一个值,然后稍后按以下方式检索它:

I'd like to store a value in AnyObject then retrieve it later as follows:

var obj:AnyObject = UIButton()
obj.setValue("James", forKey: "owner")
obj.valueForKey("owner")

但是,即使这些方法可用(如错误所示),AnyObject也不允许:

However, AnyObject does not allow it even if these methods are available as shown by the error:

setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key owner.'

这怎么办?

推荐答案

您不能分配给UIButton的任意键.一些类确实允许这样做(当然会想到CALayer和CAAnimation,当然还有NSDictionary),但是UIButton和AnyObject都不是这样的类,并且都没有 owner 属性—因此尝试设置它是无稽之谈.,这就是导致运行时崩溃的原因.您可以使用键设置按钮的 existing 属性,但不能像这样发明自己的键.

You cannot assign to an arbitrary key of a UIButton. Some classes do permit this (CALayer and CAAnimation come to mind, and NSDictionary of course), but neither UIButton nor AnyObject is such a class, and neither has an owner property — so trying to set it is nonsense, and that is what causes the crash at runtime. You can set a button's existing property using a key, but you can't just invent your own key like this.

这篇关于在Swift中,对于AnyObject,我如何先setValue()然后调用valueForKey()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆