我应该为 Objective C 数组对象设置协议以避免编译器警告吗?

发布于 2024-09-08 03:06:37 字数 270 浏览 0 评论 0原文

我有一个类,我们称之为 ABC,具有 NSArray *objects 属性,NSArray 中的对象可以是两个不同类 X 和 Y 之一。X 和 Y 都有一个 path 属性,但编译器不知道这一点。

因此,即使 ABC 总是会在我的数组对象上找到 path 属性,我的代码也会收到编译器警告 - “未找到 'path' 方法”。应用程序运行良好,但我对警告感到恼火。如何修复我的代码(使用协议?)以便编译器停止抱怨?

谢谢你!

I have a class, let's call it ABC, with an NSArray *objects property, and the objects in the NSArray can be one of two different classes, X and Y. Both X and Y have a path property, but the compiler doesn't know this.

Therefore, even though ABC will always find the path property on my array objects, I get compiler warnings on my code -- "No 'path' method found". App runs fine but I'm getting annoyed by the warnings. How can I fix my code (with protocols?) so that the compiler stops complaining?

Thank you!

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

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

发布评论

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

评论(3

梦里兽 2024-09-15 03:06:37

您需要导入一些声明 path 方法的标头。当编译代码时,编译器会查看该文件所知道的方法列表,发现没有 path 方法。您只需要告诉它该方法存在并且其签名是什么,编译器就会满意。无需协议。

You need to import some header that declares a path method. When it's compiling your code, the compiler looks at the list of methods this file knows about and it sees that there is no path method. You just need to tell it that the method exists and its signature is whatever and the compiler will be satisfied. No protocol is necessary.

送君千里 2024-09-15 03:06:37

X 和 Y 是否都派生自包含“路径”的同一个超类?如果“路径”在概念上是相同的值并且 X 和 Y 通过该值相关,那么它应该位于超类或协议中。

此外,您还可以使用 NSKeyValueCoding 协议通过 - (id)valueForKey:(NSString *)key 按字符串直接访问值。但是,使用此方法确实会失去任何类型安全性。

Do both X and Y derive from the same super class that contains "path"? If "path" is conceptually the same value AND X and Y are related by this value, then it should either be in a super class or protocol.

Additionally you can use NSKeyValueCoding protocol to directly access values by string via - (id)valueForKey:(NSString *)key. You do lose any type safety using this method, however.

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