目标C中的私有财产

Yur*_*rie 67 objective-c

有没有办法在Objective C中声明私有属性?目标是从合成的getter和setter中获益,实现某种内存管理方案,但不暴露给公众.

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

@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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ams 98

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

MyClass.m

@interface MyClass ()

@property (nonatomic, retain) NSArray *someArray;

@end

@implementation MyClass

@synthesize someArray;

...
Run Code Online (Sandbox Code Playgroud)

这就是你所需要的.

  • "这就是你所需要的." :D从未使用过如此多的代码来定义一个简单的属性 (30认同)
  • 这些天你甚至不需要`@ synthesize`. (11认同)
  • 为了扩展这一点,Objective-C实际上没有私有方法的概念.只要您知道名称,就可以调用任何您喜欢的方法.这允许您在Apple的类中调用私有方法,即使它们在标头中不存在. (4认同)
  • 确保不要像这样在 .m 文件中为您的类别设置名称`@interface MyClass (DontPutMeHere)`,否则自动合成将不起作用 (3认同)

Osp*_*pho 10

A.如果你想要一个完全私有的变量.不要给它一个财产.
B.如果您想要一个可从类的封装外部访问的只读变量,请使用全局变量和属性的组合:

//Header    
@interface Class{     
     NSObject *_aProperty     
}

@property (nonatomic, readonly) NSObject *aProperty;

// In the implementation    
@synthesize aProperty = _aProperty; //Naming convention prefix _ supported 2012 by Apple.
Run Code Online (Sandbox Code Playgroud)

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

Class *c = [[Class alloc]init];    
NSObject *obj = c.aProperty;     //Readonly
Run Code Online (Sandbox Code Playgroud)

但在内部我们无法在类中设置aProperty:

// 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
Run Code Online (Sandbox Code Playgroud)


Rog*_*Rog 6

正如其他人所指出的那样,(目前)无法在Objetive-C中真正宣布私有财产.

您可以尝试以某种方式"保护"属性的一件事是使一个基类具有声明为的属性,readonly并且在您的子类中,您可以重新声明相同的属性readwrite.

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


Ano*_*mie 5

这取决于你所说的"私人".

如果您只是表示"未公开记录",则可以轻松地在私有标头或.m文件中使用类扩展.

如果你的意思是"别人根本无法打电话",那你就不走运了.任何人都可以在知道其名称的情况下调用该方法,即使它没有公开记录.