当属性存在时,ivar 的目的是什么? [英] What's the purpose of an ivar when a property exists?

查看:23
本文介绍了当属性存在时,ivar 的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下内容不会在编译或运行时抱怨没有 name ivar.那么为什么看到 ivar @property/@synthesize 如此普遍.

The following doesn't complain at compilation nor runtime about no name ivar. So why is it so common to see an ivar and @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,我会收到警告:

In fact, if i access p->name, i get a warning:

warning: instance variable 'name' is @private; this will be a hard error in the future

这表明如果不存在 ivar,则会为我创建一个.

which indicates that an ivar is created for me if one doesn't exist.

如果这是真的,那么手动创建 ivar 有什么意义(忽略显而易见的,有时不使用 g/setter 访问器的正当理由)?

If that's true, what's the point of creating the ivar manually (ignoring the obvious, that there are sometimes valid reasons for not using the g/setter accessor)?

或者换个说法,当我需要绕过访问器时,我是否应该为一个属性创建一个 ivar?

Or asked differently, should i only ever create an ivar for a property when i need to bypass the accessors?

推荐答案

合成 ivars(不手动声明 ivars 的能力)是新的 Objective-C 运行时的一个特性,它仍然没有在所有系统上使用.对于 32 位 Mac(以及直到最近的 iPhone 模拟器),您必须手动声明 ivars.如果您只针对具有新运行时的系统,则没有理由手动声明 ivars.

Synthesized ivars (the ability to not manually declare ivars) are a feature of the new Objective-C runtime, which still isn't being used on all systems. For 32-bit Macs (and, until recently, the iPhone simulator), you have to manually declare ivars. If you're only targeting systems with the new runtime, there's no reason to manually declare ivars.

这篇关于当属性存在时,ivar 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆