Is there a way to declare a private property in Objective C? The goal is to benefit from synthesized getters and setters implementing a certain memory management scheme, yet not exposed to public.
An attempt to declare a property within a category leads to an error:
@interface MyClass : NSObject {
NSArray *_someArray;
}
...
@end
@interface MyClass (private)
@property 开发者_StackOverflow中文版(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
I implement my private properties like this.
MyClass.m
@interface MyClass ()
@property (nonatomic, retain) NSArray *someArray;
@end
@implementation MyClass
@synthesize someArray;
...
That's all you need.
A. If you want a completely private variable. Don't give it a property.
B. If you want a readonly variable that is accessible external from the encapsulation of the class, use a combination of the global variable and the property:
//Header
@interface Class{
NSObject *_aProperty
}
@property (nonatomic, readonly) NSObject *aProperty;
// In the implementation
@synthesize aProperty = _aProperty; //Naming convention prefix _ supported 2012 by Apple.
Using the readonly modifier we can now access the property anywhere externally.
Class *c = [[Class alloc]init];
NSObject *obj = c.aProperty; //Readonly
But internally we cannot set aProperty inside the Class:
// 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
It depends what you mean by "private".
If you just mean "not publicly documented", you can easily enough use a class extension in a private header or in the .m file.
If you mean "others are not able to call it at all", you're out of luck. Anyone can call the method if they know its name, even if it is not publicly documented.
As others have indicated, (currently) there is no way to truly declare a private property in Objetive-C.
One of the things you can do to try and "protect" the properties somehow is to have a base class with the property declared as readonly
and in your subclasses you can redeclare the same property as readwrite
.
Apple's documentation on redeclared properties can be found here: http://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW19
精彩评论