Что “@private” означает в Objective C?

Доступ к энергозависимой переменной действует так, как если бы она была синхронизирована сама по себе.

Доступ к энергозависимой переменной никогда не удерживает блокировку, он не подходит для случаев, когда мы хотим читать-обновлять-записывать как элементарную операцию. Здесь необходимо использовать синхронизированный блок.

Для других случаев будет достаточно, если вы не использовали синхронизацию (как обычные get и set)

279
задан Jeff Wolski 15 March 2016 в 20:20
поделиться

2 ответа

Это модификатор видимости - это означает, что переменные экземпляра объявлены как @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. Однако есть способы «скрыть» объявления методов - см. этот вопрос для получения дополнительной информации.

187
ответ дан 23 November 2019 в 02:02
поделиться

As htw said, it's a visibility modifier. @private means that the ivar (instance variable) can only be accessed directly from within an instance of that same class. However, that may not mean much to you, so let me give you an example. We'll use the init methods of the classes as examples, for simplicity's sake. I'll comment inline to point out items of interest.

@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;
}

So to answer your question, @private protects ivars from access by an instance of any other class. Note that two instances of MyFirstClass could access all of each other's ivars directly; it is assumed that since the programmer has complete control over this class directly, he will use this ability wisely.

162
ответ дан 23 November 2019 в 02:02
поделиться