合成没有实例变量的属性 [英] Synthesizing a property without instance variables

查看:72
本文介绍了合成没有实例变量的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我了解@property和@synthesize,但是我做了一些实验,无法弄清楚下面的代码(为什么我认为已被破坏)为什么起作用.

I thought I understood @property and @synthesize, but I did some experimenting and I can't figure out why the below (what I thought was broken) code works.

如您所见,没有与name属性对应的实例变量.如果找不到相同名称和类型的实例变量,Objective-C会以某种方式创建实例变量吗?

As you can see, there's no instance variable that corresponds to the name property. Does Objective-C somehow create an instance variable if it doesn't find an instance variable with the same name and type?

标题:

#import <Foundation/Foundation.h>

@interface AddressCard : NSObject {

}

@property (copy, nonatomic) NSString *name;
-(void) print;

@end

实施:

#import "AddressCard.h"

@implementation AddressCard

@synthesize name;

-(void) print {
    NSLog(@"Name=%@", self.name);
}

-(void) dealloc {
    [name release];
    [super dealloc];
}

@end

测试:

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    AddressCard *ac = [[AddressCard alloc] init];
    ac.name = @"Brandon";
    [ac print];

    [ac release];

    [pool drain];
    return 0;
}

推荐答案

快速答案是:是".在Objective-C 2.0中,综合属性将根据需要自动创建相应的ivars.

The quick answer is: "yes". In Objective-C 2.0, synthesized properties will automatically create the corresponding ivars as required.

重要提示: :如 Tommy (注意:是来自旧版文档-请参阅

Important: As pointed out by Tommy (note: this is from the legacy docs - please see the latest information):

在Objective-C 2.0的任何现代运行时(即Intel 64bit和ARM)上,可以动态地"(即在运行时但仅在创建任何实例之前)将属性添加到类中-动态比较时不特别到剩余的运行时间).但是,这不能在两个较早的运行时(即Intel 32bit和PowerPC)中的任何一个上完成.因此,实际上并不是要在Mac的运输软件上或iOS的开发过程中使用的东西(因为模拟器是32位Intel应用程序,并且无法在运行时创建实例变量)

In Objective-C 2.0 on either of the modern runtimes (ie, Intel 64bit and ARM) properties can be added to classes 'dynamically' (that is, at runtime but only before the creation of any instances — not particularly dynamic compared to the rest of the runtime). However, this can't be done on either of the two older runtimes (ie, Intel 32bit and PowerPC). It's therefore not really something you want to use on shipping software for the Mac or during development for iOS (since the simulator is a 32bit Intel application and can't create instance variables at runtime)

这篇关于合成没有实例变量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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