我试图在 Private
类别中声明仅供内部使用的属性:
@interface BarLayer (Private)
@property (readwrite, retain) MenuItemFont *menuButton;
@property (readwrite, retain) Menu *menuMenu;
@property (readwrite, retain) LabelAtlas *messageLabel;
@end
现在我正试图找出我应该在哪里 @synthesize
那些。
我试过:
@implementation BarLayer (Private)
@synthesize menuButton = _menuButton;
@synthesize menuMenu = _menuMenu;
@synthesize messageLabel = _messageLabel;
@end
在这里,编译器提示:
@synthesize not allowed in a category's implementation
所以我试着把它放在我的 BarLayer
实现中,但是在这里它没有找到 BarLayer
接口(interface)中的声明。
no declaration of property ‘menuButton’ found in the interface
正确的方法是什么?
最佳答案
不能对类别使用 @synthesize
。
您可以使用类扩展(又名匿名类别)执行此操作,它只是一个没有名称的类别,其方法必须在主 @implementation
block 中实现对于那个类(class)。对于您的代码,只需将“(Private)”更改为“()”并在主 @implementation
block 中使用 @synthesize
以及该类的其余代码.
参见 the Apple docs on extensions有关更多信息。 (显然这是 Mac OS 10.5 中的新功能。)
编辑:一个例子:
// Main interface (in .h)
@interface Foo : NSObject
- (void)bar;
@end
// Private interface (in .m, or private .h)
@interface Foo ()
@property (nonatomic, copy) NSString *myData;
@end
@implementation Foo
@synthesize myData; // only needed for Xcode 4.3 and earlier
- (void)bar { ... }
@end
另一种解决方案(工作量更大)是使用 objc_setAssociatedObject
和 objc_getAssociatedObject
伪造额外的实例变量。在这种情况下,您可以将它们声明为属性,并使用上面的 objc_* 运行时方法自己实现 setter 和 getter。有关这些功能的更多详细信息,请参阅 the Apple docs on Objective-C runtime .
关于objective-c - 隐藏公共(public)访问的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743586/