我试图在我的 *.m
文件中创建私有(private)属性:
@interface MyClass (Private)
@property (nonatomic, retain) NSMutableArray *stuff;
@end
@implementation MyClass
@synthesize stuff; // not ok
编译器声称没有声明 stuff 属性。但是有一点。只是在匿名类别中。让我猜猜:不可能。其他解决方案?
最佳答案
您想使用“类扩展”而不是类别:
@interface MyClass ()
@property (nonatomic, retain) NSMutableArray *stuff;
@end
@implementation MyClass
@synthesize stuff; // ok
在 Objective-C 2.0 中创建类扩展部分是专门为此目的而创建的。类扩展的优点是编译器将它们视为原始类定义的一部分,因此可以警告不完整的实现。
除了纯粹的私有(private)属性,您还可以创建内部可读写的只读公共(public)属性。可以在类扩展中重新声明一个属性,只是为了更改访问权限(只读与读写),但在其他声明中必须相同。因此你可以这样做:
//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
关于objective-c - 如何打造私有(private)属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2768750/