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

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


I want to use a category to make a method on the original class available as a property as well.

我想使用一个category来在原始类上创建一个方法,作为一个属性。

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?

现在,当我这样做时,它似乎起作用了(编辑:也许它不工作,它没有抱怨,但我看到了奇怪),但是它给了我警告,因为我没有在我的类别实现中合成属性。我怎么告诉编译器一切都很好因为原始的类为我合成了属性?

3 个解决方案

#1


32  

Here's the warning you're getting:

以下是你得到的警告:

warning: property ‘foo’ requires method '-foo' to be defined - use @synthesize, @dynamic or provide a method implementation

警告:属性' foo'需要方法'-foo'来定义-使用@synthesize, @dynamic或提供一个方法实现。

To suppress this warning, have this in your implementation:

为了抑制这个警告,请在您的实现中使用以下命令:

@dynamic foo;

@dynamic foo;

#2


1  

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

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

#3


1  

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. 在不触及基类的情况下,将属性添加到类别中:http://compileyouidontevenknow. blogspot.com/2012/06/adding-proper- to-class-you-dont.html。
  3. Access iVars from categories: http://compileyouidontevenknowyou.blogspot.com/2012/06/if-you-want-to-keep-everything-in-your.html
  4. 从类别中访问iVars: http://compileyouidontevenknowyou.blogspot.com/2012/06/if-you- to- to- to- keep-your.html。

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

这比使用方法(至少是)更安全的方法要好得多。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2010/03/26/3417480f8b5279f942603142b83d020b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告