目标C中的私有财产

有没有办法在Objective C中声明一个私有属性? 其目标是从合成的获取者和设置者中获益,实现一定的内存pipe理scheme,但不公开。

尝试在类别中声明属性会导致错误:

@interface MyClass : NSObject { NSArray *_someArray; } ... @end @interface MyClass (private) @property (nonatomic, retain) NSArray *someArray; @end @implementation MyClass (private) @synthesize someArray = _someArray; // ^^^ error here: @synthesize not allowed in a category's implementation @end @implementation MyClass ... @end 

我实现了这样的私有属性。

MyClass.m

 @interface MyClass () @property (nonatomic, retain) NSArray *someArray; @end @implementation MyClass @synthesize someArray; ... 

这就是你所需要的。

答:如果你想要一个完全私人的variables。 不要给它一个财产。
B.如果你想要一个从类的封装外部访问的只读variables,使用全局variables和属性的组合:

 //Header @interface Class{ NSObject *_aProperty } @property (nonatomic, readonly) NSObject *aProperty; // In the implementation @synthesize aProperty = _aProperty; //Naming convention prefix _ supported 2012 by Apple. 

使用readonly修饰符,我们现在可以在外部任何地方访问属性。

 Class *c = [[Class alloc]init]; NSObject *obj = c.aProperty; //Readonly 

但在内部我们不能在类中设置一个属性:

 // In the implementation self.aProperty = [[NSObject alloc]init]; //Gives Compiler warning. Cannot write to property because of readonly modifier. //Solution: _aProperty = [[NSObject alloc]init]; //Bypass property and access the global variable directly 

正如其他人所指出的,(目前)在Objetive-C中没有办法真正地申报私有财产。

你可以做的事情之一,试图“保护”属性莫名其妙地是有一个基类声明为readonly的属性,在你的子类中,你可以重新声明相同的属性为readwrite

苹果关于重新声明的属性的文档可以在这里find: http : //developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17- SW19

这取决于你所说的“私人”。

如果你的意思是“没有公开logging”,你可以很容易地在私有头文件或.m文件中使用类扩展 。

如果你的意思是“别人根本就不能打电话”,那你倒霉了。 如果知道它的名字,即使没有公开logging,任何人都可以调用该方法。