@private在Objective-C中是什么意思?


它是一个可见性修饰符——这意味着声明为@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的两个实例可以直接访问彼此的所有变量;假定由于程序员直接完全控制这个类,他将明智地使用这种能力。


当有人说您不能访问@private实例变量时,理解这意味着什么非常重要。实际情况是,如果您试图在源代码中访问这些变量,编译器将会给您一个错误。在GCC和XCode的早期版本中,你只会得到警告而不是错误。

无论哪种方式,在运行时,所有的赌注都消失了。这些@private和@protected ivar可以被任何类的对象访问。这些可见性修饰符使得将源代码编译成违背可见性修饰符意图的机器码变得困难。

不要依赖于ivar可见性修饰符的安全性!他们什么也不提供。它们严格用于类构建器愿望的编译时强制执行。