我应该为 Objective C 数组对象设置协议以避免编译器警告吗?
我有一个类,我们称之为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要导入一些声明
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 nopath
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.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.