Answers:
这是可见性修饰符 -意味着声明为的实例变量@private
只能由同一类的实例访问。子类或其他类不能访问私有成员。
例如:
@interface MyClass : NSObject
{
@private
int someVar; // Can only be accessed by instances of MyClass
@public
int aPublicVar; // Can be accessed by any object
}
@end
另外,为了澄清起见,方法在Objective-C中始终是公共的。但是,有多种方法可以“隐藏”方法声明- 有关更多信息,请参见此问题。
正如htw所说,它是可见性修改器。 @private
意味着只能从同一类的实例中直接访问ivar(实例变量)。但是,这对您可能并不重要,所以让我举个例子。init
为了简单起见,我们将使用类的方法作为示例。我将内联注释以指出感兴趣的项目。
@interface MyFirstClass : NSObject
{
@public
int publicNumber;
@protected // Protected is the default
char protectedLetter;
@private
BOOL privateBool;
}
@end
@implementation MyFirstClass
- (id)init {
if (self = [super init]) {
publicNumber = 3;
protectedLetter = 'Q';
privateBool = NO;
}
return self;
}
@end
@interface MySecondClass : MyFirstClass // Note the inheritance
{
@private
double secondClassCitizen;
}
@end
@implementation MySecondClass
- (id)init {
if (self = [super init]) {
// We can access publicNumber because it's public;
// ANYONE can access it.
publicNumber = 5;
// We can access protectedLetter because it's protected
// and it is declared by a superclass; @protected variables
// are available to subclasses.
protectedLetter = 'z';
// We can't access privateBool because it's private;
// only methods of the class that declared privateBool
// can use it
privateBool = NO; // COMPILER ERROR HERE
// We can access secondClassCitizen directly because we
// declared it; even though it's private, we can get it.
secondClassCitizen = 5.2;
}
return self;
}
@interface SomeOtherClass : NSObject
{
MySecondClass *other;
}
@end
@implementation SomeOtherClass
- (id)init {
if (self = [super init]) {
other = [[MySecondClass alloc] init];
// Neither MyFirstClass nor MySecondClass provided any
// accessor methods, so if we're going to access any ivars
// we'll have to do it directly, like this:
other->publicNumber = 42;
// If we try to use direct access on any other ivars,
// the compiler won't let us
other->protectedLetter = 'M'; // COMPILER ERROR HERE
other->privateBool = YES; // COMPILER ERROR HERE
other->secondClassCitizen = 1.2; // COMPILER ERROR HERE
}
return self;
}
因此,要回答您的问题,@ private可以防止ivars被任何其他类的实例访问。请注意,MyFirstClass的两个实例可以直接访问彼此的所有ivars。假定由于程序员可以直接完全控制此类,因此他将明智地使用此功能。
@private
对象的模板放入其中,因此它不再是常见的。
@implementation
块上。一旦执行此操作,无论可见性修饰符如何,它们实际上都是私有的,因为该文件之外的任何人都看不到它们。