@private
在Objective-C中意味着什么?
答案 0 :(得分:185)
这是可见性修饰符 - 这意味着声明为@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中的方法总是公开的。有一些方法可以“隐藏”方法声明,但请参阅this question以获取更多信息。
答案 1 :(得分:162)
正如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;假设程序员直接完全控制了这个类,他会明智地使用这个能力。
答案 2 :(得分:14)
当有人说你无法访问@private
实例变量时,了解它意味着什么很重要。真实的情况是,如果您尝试在源代码中访问这些变量,编译器将给您一个错误。在以前的GCC和XCode版本中,您只会收到警告而不是错误。
无论哪种方式,在运行时,所有投注均已关闭。这些@private
和@protected
ivars可以由任何类的对象访问。这些可见性修饰符使得难以将源代码编译为违反可见性修饰符意图的机器代码。
不要依靠ivar可见性修饰符来保证安全!它们根本没有提供。它们严格用于编译时执行类构建器的愿望。