开发者

Objective-C categories: Can I add a property for a method not in my category?

开发者 https://www.devze.com 2022-12-25 04:07 出处:网络
I want to use a category to make a method on the original class available as a property as well. Class A:

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?


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.

  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消