有没有办法在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)
这就是你所需要的.
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)
正如其他人所指出的那样,(目前)无法在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