How to make a private property?
I tried to make a private property in my *.m
file:
@interface MyClass (Private开发者_StackOverflow中文版)
@property (nonatomic, retain) NSMutableArray *stuff;
@end
@implementation MyClass
@synthesize stuff; // not ok
Compiler claims that there's no stuff property declared. But there's a stuff. Just in an anonymous category. Let me guess: Impossible. Other solutions?
You want to use a "class extension" rather than a category:
@interface MyClass ()
@property (nonatomic, retain) NSMutableArray *stuff;
@end
@implementation MyClass
@synthesize stuff; // ok
Class extensions were created in Objective-C 2.0 in part specifically for this purpose. The advantage of class extensions is that the compiler treats them as part of the original class definition and can thus warn about incomplete implementations.
Besides purely private properties, you can also create read-only public properties that are read-write internally. A property may be re-declared in a class extensions solely to change the access (readonly vs. readwrite) but must be identical in declaration otherwise. Thus you can do:
//MyClass.h
@interface MyClass : NSObject
{ }
@property (nonatomic,retain,redonly) NSArray *myProperty;
@end
//MyClass.m
@interface MyClass ()
@property (nonatomic, retain, readwrite) NSArray *myProperty;
@end
@implementation MyClass
@synthesize myProperty;
//...
@end
精彩评论