objective-c - 隐藏公共(public)访问的属性

标签 objective-c

我试图在 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_setAssociatedObjectobjc_getAssociatedObject 伪造额外的实例变量。在这种情况下,您可以将它们声明为属性,并使用上面的 objc_* 运行时方法自己实现 setter 和 getter。有关这些功能的更多详细信息,请参阅 the Apple docs on Objective-C runtime .

关于objective-c - 隐藏公共(public)访问的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743586/

相关文章:

objective-c - 在 C 风格方法中访问实例变量

iphone - 如何为特定文件添加 ARC?

ios - didSelectRowAtIndexPath 不工作

iphone - 使用 Restkit 为 NSManagedObject 类创建实例

ios - 仍然没有收到来自 fabric for twitter 的电子邮件

ios - 代表申报困境

ios - ObjC/iOS - 大写每个单词的首字母而不修改其他字母

objective-c - iOS 5 Storyboard和 Nibs

iOS 动画问题

ios - CoreData - 在后台上下文中删除对象时的不一致行为(附加测试项目)