gpt4 book ai didi

iOS自动@synthesize而不创建ivar

转载 作者:技术小花猫 更新时间:2023-10-29 10:06:35 26 4
gpt4 key购买 nike

如果我有一个 @property 而我不想通过 ivar 支持我只是省略了 @synthesize 并且有返回计算值的手动 getter。

但是,从 Xcode 4.4 开始,如果我不指定 @synthesize,编译器将自动生成它。这是否意味着即使我不需要/不使用它,它也会生成一个 ivar

我最终可以使用 dynamic 强制不自动合成。然而,这是错误的,因为如果 getter and setter are implemented somewhere else or during runtime@dynamic 应该用于关闭警告。 .

最佳答案

在我的工作中,我注意到以下行为。

  1. 如果您有读写属性,没有 @synthesize,有 getter 而没有 setter,那么它将生成 iVar。
  2. 如果您有读写属性,没有@synthesize,没有getter,但有setter,那么它将生成iVar。
  3. 如果您有读写属性,没有 @synthesize 并且同时有 getter 和 setter,那么它不会生成 iVar。
  4. 如果您有只读属性,没有 @synthesize 也没有 getter,那么它将生成 iVar。
  5. 如果您有只读属性,没有 @synthesize 并且有 getter,那么它不会生成 iVar。

据此,我认为一般规则是,如果您没有@synthesize,并且拥有完全实现该属性所需的所有方法,那么它会被假定为动态的并且不会't 生成 iVar。

无论如何,如果您想确保不生成 iVar,则将其声明为 @dynamic


对@dynamic的澄清

来自 Declared PropertiesThe Objective-C Programming Language :

You use the @dynamic keyword to tell the compiler that you will fulfill the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution.

对我来说,即使您直接实现 getter 和 setter,也可以将属性标记为 @dynamic。

关于iOS自动@synthesize而不创建ivar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12933785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com