Objective-C 类别:我可以为不属于我的类别的方法添加属性吗?

发布于 2024-08-26 19:39:13 字数 391 浏览 4 评论 0原文

我想使用类别来使原始类上的方法也可用作属性。

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 技术交流群。

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

发布评论

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

评论(3

没有心的人 2024-09-02 19:39:13

这是您收到的警告:

警告:属性'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;

猛虎独行 2024-09-02 19:39:13

如果在类别的接口中声明了某些内容,则其定义属于您的类别的实现。

If something's declared in your category's interface, its definition belongs in your category's implementation.

给我一枪 2024-09-02 19:39:13

我就此写了两篇文章,尽管这个概念与您提出的问题略有不同。

  1. 在不触及基类的情况下向类别添加属性: http ://compileyouidontevenknowyou.blogspot.com/2012/06/adding-properties-to-class-you-dont.html
  2. 从类别访问 iVar:http://compileyouidontevenknowyou.blogspot.com/2012/06/if-you-want-to- keep-everything-in-your.html

这比方法调配要好得多,至少:更安全。

I wrote two articles on this, though the concept is slightly different from the question you're asking.

  1. Add properties to categories without touching the base class: http://compileyouidontevenknowyou.blogspot.com/2012/06/adding-properties-to-class-you-dont.html
  2. Access iVars from categories: http://compileyouidontevenknowyou.blogspot.com/2012/06/if-you-want-to-keep-everything-in-your.html

This is a LOT better than method swizzling, at least: way safer.

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