问题 ObjectiveC:在哪里声明私有实例属性?


我有以下类接口:

@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

谢谢!


11969
2017-07-03 04:09


起源

您可以在这里找到许多问题的好答案: stackoverflow.com/search?q=private+property - Monolo
可能重复 如何建造私人物业? - Monolo


答案:


您不必在接口和实现中声明您的ivars。因为您想将它们设为私有,您可以在实现文件中声明它们,如下所示:

@implementation {

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

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

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


6
2017-07-03 06:27





我通常在实施中“强制”私有扩展

在你的标题中

@interface MyClass : NSObject
{
}

@property (nonatomic, assign) int publicProperty;

@end

在您的实现文件中:

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


@implementation MyClass
@synthesize privateProperty;
@synthesize publicProperty;

@end

9
2017-07-03 13:27





你的意思是你想声明私有实例变量?

你可以这样做:

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

0
2017-07-03 04:12



是的,但我不想把它变成ivar,它只是一个属性,可以通过self.privateProperty使用访问器访问,而不是在@interface中公开。 - hzxu
你不能这样做 @property int privateProperty = _privateProperty;,您必须在实现文件中执行此操作。 - Anna Fortuna


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

0
2017-07-03 08:22