Objective-C 类别:我可以为不属于我的类别的方法添加属性吗?
我想使用类别来使原始类上的方法也可用作属性。
A 类:
@interface ClassA
- (NSString*)foo;
@end
A 类类别
@interface ClassA (Properties)
- (void)someCategoryMethod;
@property (nonatomic, readonly) NSString *foo;
@end
现在,当我这样做时,它似乎可以工作(编辑:也许它不起作用,它不会抱怨,但我看到了奇怪的情况),但它给了我警告因为我没有在我的类别实现中综合该属性。我如何告诉编译器一切实际上都很好,因为原始类为我合成了属性?
I want to use a category to make a method on the original class available as a property as well.
Class A:
@interface ClassA
- (NSString*)foo;
@end
Class A category
@interface ClassA (Properties)
- (void)someCategoryMethod;
@property (nonatomic, readonly) NSString *foo;
@end
Now when I do this, it seems to work (EDIT: Maybe it doesn't work, it doesn't complain but I am seeing strangeness), but it gives me warnings because I am not synthesizing the property in my category implementation. How do I tell the compiler everything is actually just fine since the original class synthesizes the property for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是您收到的警告:
警告:属性'foo'需要定义方法'-foo' - 使用@synthesize,@dynamic或提供方法实现
要抑制此警告,请将其包含在您的实现:
@dynamic foo;
Here's the warning you're getting:
warning: property ‘foo’ requires method '-foo' to be defined - use @synthesize, @dynamic or provide a method implementation
To suppress this warning, have this in your implementation:
@dynamic foo;
如果在类别的接口中声明了某些内容,则其定义属于您的类别的实现。
If something's declared in your category's interface, its definition belongs in your category's implementation.
我就此写了两篇文章,尽管这个概念与您提出的问题略有不同。
这比方法调配要好得多,至少:更安全。
I wrote two articles on this, though the concept is slightly different from the question you're asking.
This is a LOT better than method swizzling, at least: way safer.