我有以下类接口:
@interface MyClass : NSObject
@property int publicProperty;
@end
那么实施:
@interface MyClass() // class extension
- (void)privateMethod; // private methods
@end
@implementation MyClass {
int _privateProperty;
}
@property int privateProperty = _privateProperty;
@end
这就是Apple在WWDC中展示的内容,但是有没有理由不将_privateProperty放在类扩展中,如:
@interface MyClass() // class extension
{
int _privateProperty;
}
- (void)privateMethod; // private methods
@end
谢谢!
您不必在接口和实现中声明您的ivars。因为您想将它们设为私有,您可以在实现文件中声明它们,如下所示:
@implementation {
int firstVariable;
int secondVariable;
...
}
//properties and code for your methods
如果您愿意,可以创建getter和setter方法,以便可以访问这些变量。
你说话的人是对的,以为没有任何理由你不会在界面中以相同的方式声明它们。有些书实际上告诉你,@ interface显示了班级的公众形象,你在实施中所拥有的将是私人的。
我通常在实施中“强制”私有扩展
在你的标题中
@interface MyClass : NSObject
{
}
@property (nonatomic, assign) int publicProperty;
@end
在您的实现文件中:
@interface MyClass ()
@property (nonatomic, assign) int privateProperty;
@end
@implementation MyClass
@synthesize privateProperty;
@synthesize publicProperty;
@end
你的意思是你想声明私有实例变量?
你可以这样做:
@interface MyClass()
{
@private //makes the following ivar private
int _privateProperty;
}
使用“现代运行时”(64位MacOS post-10.5和所有版本的iOS),您根本不需要声明实例变量。
// MyClass.h
@interface MyClass : NSObject
@property int publicProperty;
@end
// MyClass.m
@implementation MyClass
@synthesize publicProperty = _privateProperty; // int _privateProperty is automatically synthesized for you.
@end