如何建造私人物业?

don*_*ile 8 properties objective-c

我试图在我的*.m文件中创建一个私有属性:

@interface MyClass (Private)
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // not ok
Run Code Online (Sandbox Code Playgroud)

编译器声称没有声明stuff属性.但有一些东西.只是在匿名类别.让我猜:不可能.其他方案?

Bar*_*ark 14

您想使用"类扩展"而不是类别:

@interface MyClass ()
@property (nonatomic, retain) NSMutableArray *stuff;
@end

@implementation MyClass
@synthesize stuff; // ok
Run Code Online (Sandbox Code Playgroud)

类扩展是在Objective-C 2.0中创建的,部分专门用于此目的.类扩展的优点是编译器将它们视为原始类定义的一部分,因此可以警告不完整的实现.

除了纯私有属性,您还可以创建内部读写的只读公共属性.可以在类扩展中重新声明属性,仅用于更改访问权限(readonly与readwrite),但在声明中必须相同.这样你就可以做到:

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