现代 Objective C 运行时中 ivar 合成的底层机制是什么
现代(64 位 OS X 和 iPhone OS)Objective C 运行时的功能之一是属性能够动态合成 ivars,而无需在类中显式声明它们:
@interface MyClass : NSObject {
// NSString *name; unnecessary on modern runtimes
}
@property (retain) NSStrng *name;
@end
@implementation MyClass
@synthesize name;
@end
在我的相当多的代码中,我使用自定义 getter 实现,以便初始化属性:
- (NSString *) name {
if (!name) {
name = @"Louis";
}
return name;
}
上面的内容与合成的 ivar 不兼容,因为它需要访问未在标头中声明的 ivar。 由于各种原因,我想更新一些我的个人框架,以便在现代运行时构建时使用合成的 ivars,需要修改上述代码以使用合成的 ivars 才能实现该目标。
虽然 Objective C 2.0 文档指出现代运行时的合成访问器将在首次使用时合成 ivar。 它没有指定使用什么低级机制来执行此操作。 它是由 class_getInstanceVariable() 完成的吗?对 class_addIvar() 的限制是否放宽?它是 Objective C 2.0 运行时中未记录的函数吗? 虽然我可以为支持我的属性的数据实现自己的侧面存储,但我更愿意使用合成访问器正在使用的机制。
One of the features of the modern (64 bit OS X and iPhone OS) Objective C runtime is the ability for properties to dynamically synthesize ivars without explicitly declaring them in the class:
@interface MyClass : NSObject {
// NSString *name; unnecessary on modern runtimes
}
@property (retain) NSStrng *name;
@end
@implementation MyClass
@synthesize name;
@end
In quite a bit of my code I use custom getter implementations in order to initialize the properties:
- (NSString *) name {
if (!name) {
name = @"Louis";
}
return name;
}
The above is incompatible with synthesized ivars since it needs to access a an ivar that is not declared in the header. For various reasons I would like to update a number of my personal frameworks to use synthesized ivars when built on the modern runtimes, the above code needs to be modified to work with synthesized ivars in order to achieve that goal.
While the Objective C 2.0 documentation states that the synthesized accessors on the modern runtime will synthesize the ivar on first use. It does not specify what low level mechanism is used to do this. Is it done by class_getInstanceVariable(), are the restrictions on class_addIvar() loosened, is it an undocumented function int he objective C 2.0 runtime? While I could implement my own side storage for the data backing my properties, I would much rather use the mechanism that synthesized accessors are using.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我刚才又去看了文档,我认为你误读了。 综合的 ivar 是在编译时创建的,而不是在运行时创建的。
根据 Objective-C 2.0 文档:
因此,您需要做的就是声明您需要的实例变量,并且相同的代码将在两个运行时上运行......
I went and looked at the documentation again just now, and I think you're misreading it. Synthesized ivars are created at compile time, not at run time.
According to the Objective-C 2.0 documentation:
So all you need to do is declare the instance variable you need, and the same code will work on both runtimes...
您正在寻找的是@synthesized名称,例如:
What you are looking for is @synthesized name, like:
您可以在运行时使用 NSKeyValueCoding 协议。
You add properties at run-time with the NSKeyValueCoding Protocol.