iPhone Simulator:使用合成实例变量时出现构建错误
Cocoa/Objective-C 有两种运行时:传统运行时和“现代”运行时(Apple 称之为)。
根据 Apple文档,“Mac OS X v10.5 及更高版本上的 iPhone 应用程序和 64 位程序使用现代版本的运行时”。
到目前为止,一切都很好。
现在,“现代”运行时支持一项称为“合成实例变量”的功能,这意味着您不必为每个声明的属性定义实例变量。 实例变量将自动添加。 引自 iPhone 参考库: “对于现代运行时,实例变量是根据需要合成的。如果同名的实例变量已经存在,则使用它。”
如果您在 iPhone 应用程序中使用此功能,它将构建并运行在 iPhone(物理)设备上很好,但是当您将目标更改为“iPhone Simulator”时,您会收到构建错误:
合成属性“x”必须与兼容的 ivar 命名相同,或者必须显式命名 ivar
这是怎么回事? iPhone模拟器不是真正的iPhone模拟器吗? 这是否意味着模拟器使用与物理 iPhone 不同的运行时?
如何在 iPhone 模拟器上使用此功能?
编辑:以
iPhone 模拟器为目标时无法编译的代码是:
@interface MyClass : NSObject {
}
@property NSString *prop1;
@end
根据文档,这应该在“现代”运行时正常工作,而且确实如此在 iPhone 设备上,但将目标更改为 iPhone Simulator 时不会编译。
There are two runtimes for Cocoa/Objective-C: the legacy runtime and the "modern" runtime (that's what Apple calls it).
According to Apple's documentation, "iPhone applications and 64-bit programs on Mac OS X v10.5 and later use the modern version of the runtime".
So far so good.
Now, the "modern" runtime supports a feature called "synthesized instance variables", which means that you don't have to define an instance variable for every declared property. The instance variable will be added automatically. Quote from the iPhone Reference Library: "For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used."
If you use this feature in your iPhone app, it builds and runs fine on the iPhone (physical) device, but when you change the target to "iPhone Simulator", you get build errors:
synthesized property 'x' must either be named the same as a compatible ivar or must explicitly name an ivar
What's going on here? Isn't the iPhone simulator a real iPhone simulator? Does this mean that the simulator uses a different runtime than the physical iPhone?
How can I use this feature on the iPhone simulator?
EDIT:
The code which doesn't compile when targeting the iPhone Simulator is:
@interface MyClass : NSObject {
}
@property NSString *prop1;
@end
According to the documentation, this should work fine on the "modern" runtime, and indeed it does on the iPhone device, but it doesn't compile when changing the target to iPhone Simulator.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要有一个变量来“备份”合成属性,除非您计划自己实现该属性。
修复代码的最简单方法是添加实例变量:
You need to have a variable to 'back up' the synthesized property, unless you plan on implementing the property yourself.
The simplest way to fix your code is to add an instance variable:
当前 SDK (3.0) 中的 iPhone 模拟器使用主机的运行时,该运行时不支持 32 位模式下的合成 ivars。 在模拟器修复之前,您必须
@synthesize
您的ivars。 (最好向 Apple 提交错误以请求此增强功能。)The iPhone Simulator in current SDKs (3.0) use the host’s runtime, which does not support synthesized ivars in 32-bit mode. You’ll have to
@synthesize
your ivars until the Simulator is fixed. (It’d be good to file a bug with Apple requesting this enhancement.)