如何保证运行时协议的一致性?
@interface Dog : NSObject
@end
@implementation Dog
- (id)valueForUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"quacks"])
return YES;
}
@end
上面的代码允许利用 KVC 并编写如下内容:
[[Dog new] valueForKey:@"quacks"]; // 是
但是,objc 运行时是否可以利用相同的 KVC 机制,并在运行时遵守 Duck 协议?
@protocol Duck <NSObject>
@optional
@property (readonly) BOOL quacks;
@end
id<Duck> dug = (id<Duck>)[Dog new];
dug.quacks; // YES
@interface Dog : NSObject
@end
@implementation Dog
- (id)valueForUndefinedKey:(NSString *)key
{
if ([key isEqualToString:@"quacks"])
return YES;
}
@end
The above allows to leverage KVC and write something like :
[[Dog new] valueForKey:@"quacks"]; // YES
However, can the objc runtime be used to leverage the same KVC mechanism, AND conform to the Duck protocol at runtime ?
@protocol Duck <NSObject>
@optional
@property (readonly) BOOL quacks;
@end
id<Duck> dug = (id<Duck>)[Dog new];
dug.quacks; // YES
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定我理解你的问题,但 NSObject 上有一个方法:
你可以使用它来测试对象是否符合特定协议。对于更细粒度的控制,您可以使用:
在发送消息之前测试对象是否会响应消息。
Not sure I understand your question, but there is the method on NSObject:
You can use this to test if an object conforms to a particular protocol. For more fine grained control you can use:
to test if an object will respond to a message before sending one.
“在运行时遵守 Duck 协议”
您不能“在运行时遵守协议”。您可以使用
respondsToSelector:
检查在运行时检查选择器。但是,我相信这对于通过valueForUndefinedKey:
处理的消息仍然不起作用。"conform to the Duck protocol at runtime"
You cannot "conform to a protocol at runtime". You can use the
respondsToSelector:
check to check for a selector at runtime. However, I believe that that will still not work for messages handled viavalueForUndefinedKey:
.