【发布时间】:2010-07-26 16:38:37
【问题描述】:
以下内容不会在编译或运行时抱怨没有name ivar。那么为什么看到 ivar 和 @property/@synthesize 如此普遍。
@interface PropTest : NSObject
{
}
@property (retain) NSString *name;
@end
@implementation PropTest
@synthesize name;
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
PropTest *p = [[PropTest new] autorelease];
p.name = @"Hello, World!";
NSLog(@"%@",p.name);
[pool drain];
return 0;
}
此代码打印
Hello, World!
事实上,如果我访问p->name,我会收到警告:
warning: instance variable 'name' is @private; this will be a hard error in the future
这表示如果一个 ivar 不存在,则会为我创建一个 ivar。
如果这是真的,那么手动创建 ivar 有什么意义(忽略显而易见的问题,即有时不使用 g/setter 访问器是有正当理由的)?
或者换个说法,我应该只在需要绕过访问器时为属性创建一个ivar吗?
【问题讨论】: