我有以下代码行:
[self.someBtn setValue:@"some-value" forKey:@"some-key"];
其中 someBtn
是从 Storyboard绑定(bind)的。
问题是我收到此错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIButton 0x137e7deb0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key some-key.'
如果我评论这行代码,它就会起作用。我只想使用 setValue:forKey 函数通过 UIButton 传递一些“元”信息。
有人可以向我解释一下发生了什么吗?谢谢!
最佳答案
最简单的方法是通过关联对象“为按钮附加一些值”。您可以为 UIButton
编写一个扩展
@interface UIButton (AssociatedObject)
@property (nonatomic, strong) id associatedObject;
@end
@implementation UIButton (AssociatedObject)
@dynamic associatedObject;
- (void)setAssociatedObject:(id)object {
objc_setAssociatedObject(self, @selector(associatedObject), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (id)associatedObject {
return objc_getAssociatedObject(self, @selector(associatedObject));
}
您可以阅读 very good article on NSHipster涵盖相关对象的使用。
请注意,无论您想实际做什么,都可以通过子类化按钮或将值存储在其他地方来更轻松地完成。
关于ios - UIButton 此类与键的键值代码不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45484462/