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

查看:89
本文介绍了属性存在时,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天全站免登陆