目标C:在哪里声明私有实例属性?

时间:2012-07-03 04:09:21

标签: objective-c implementation private class-extensions

我有以下类接口:

@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

谢谢!

4 个答案:

答案 0 :(得分:10)

我通常会在实施中强制使用扩展名

在标题中

@interface MyClass : NSObject
{
}

@property (nonatomic, assign) int publicProperty;

@end

在您的实施文件中:

@interface MyClass ()
@property (nonatomic, assign) int privateProperty;
@end


@implementation MyClass
@synthesize privateProperty;
@synthesize publicProperty;

@end

答案 1 :(得分:6)

你不必在界面和实现中声明你的ivars。因为你想把它们设为私有你可以在实现文件中声明它们如下:

@implementation {

int firstVariable;
int secondVariable;
...
}
//properties and code for  your methods

如果您愿意,可以创建getter和setter方法,以便可以访问这些变量。

与你交谈的人是对的,认为你没有任何理由不在界面中以相同的方式声明它们。有些书实际上告诉你,@ interface显示了班级的公众形象,你在实施中所拥有的将是私人的。

答案 2 :(得分:0)

您的意思是要声明私有实例变量吗?

你可以这样做:

@interface MyClass()
{
 @private //makes the following ivar private
   int _privateProperty;
}

答案 3 :(得分:0)

使用“现代运行时”(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
相关问题