我可以使用协议对象作为 NSDictionary 中的键吗?

发布于 2024-09-15 09:11:03 字数 378 浏览 1 评论 0原文

我在苹果文档中读到(正如我预期的那样)NSDictionary 不仅仅局限于键的字符串。这里还有一篇文章确认可以使用 Sets。我想使用协议对象,但它没有发生。我 initWithObjectsAndKeys 并传递 @protocol(MyGreatProtocol) 作为密钥。编译,但我收到一个运行时错误,说“对象[协议对象]没有实现某些东西或其他 - 前面有麻烦”,然后另一个错误消息说“你看,我说这会导致问题。我正在摆脱困境”这!”

好吧,第二个的措辞可能略有不同,但抱歉现在不在比赛中,我想在我真正回来之前尝试澄清这一点。希望至少有人能明白我的问题的要点。

也许这是我引用协议的方式?我尝试过各种替代方案但没有成功。 @protocol(Blah) 返回一个指针?所以无法真正理解为什么它不起作用。

I've read in Apples docu that (as I expected) an NSDictionary is not constrained just to strings for keys. There's also a post here confirming that Sets can be used. I want to use protocol objects but it' not happening. I initWithObjectsAndKeys and pass @protocol(MyGreatProtocol) as a key. Compiles but I get a runtime error saying something like "object [the protocol object] doesn't implement somethingorother - trouble ahead" then another error message saying something like "You see, I said it would cause problems. I'm bailing out of this!"

Ok, the wording of the second might have been slightly different, but sorry not at the comp right now and wanted to try clarify this before I really am back at it. Hope at least somebody will get the gist of my problem.

Maybe it's the way I'm referencing the protocol? I've played around with alternatives without success. And @protocol(Blah) returns a pointer? So can't really fathom why it's not working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云归处 2024-09-22 09:11:03

您可以使用函数 NSStringFromProtocolNSProtocolFromString 如果您希望将协议名称存储在字典中。 NSStringFromProtocol 将返回一个可以用作键的字符串对象,而 NSProtocolFromString 将采用相反的方式。

字典中的键对象必须符合 NSCopying 协议,因为键在逻辑上必须是不可变的。

You can use the functions NSStringFromProtocol and NSProtocolFromString if you wish to store protocol names in a dictionary. NSStringFromProtocol will return a string object that you can use as a key, and NSProtocolFromString will go the other way.

Key objects in a dictionary must conform to the NSCopying protocol, because the keys must be logically immutable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文