如何声明一个@property,但是阻止它的ivar被创建? [英] How can I declare a @property but prevent its ivar from being created?
问题描述
我有类 A
,它暴露了获取和设置类型 Foo
的对象的方法。在属性说法中,我通常在界面中声明:
@property(nonatomic,strong)Foo * foo;
这在现代ObjC中生成访问器和一个ivar, _foo
用于存储。
如果我想在访问器中进行自定义工作,我可以自己实现一个或两个。但是,如果我不仅想做自定义工作,我实际上不想要ivar吗?换句话说,我正在使用Foo对象做其他事情,例如将它来回传递给我组成的另一个内部对象。我实际上不需要在 A
的实例中保存 foo
的存储。
看起来我有两个选择:
- 声明属性,实现两个访问器忽略编译器为
_foo
创建存储器的事实,并且不要使用它。 - 显式声明我的访问器:
- (Foo *)foo
和- (void)setFoo:
第一个看起来很像在运行时,第二个似乎不起眼(在那里我可能现在有一个混合的属性和属性的访问器)。
有一种方法
如果你重写了setter和getter,并且没有使用setter和getter中的变量,不会创建一个变量。
例如,如果你有一个类,你想要一个 firstName
和 lastName
属性,但也许还有一个 setter
和 getter
对于 fullName
属性,如果您的 fullName
c $ c> firstName 和 lastName
并将这些属性设置为(并且不会将完整字符串存储到 fullName
变量),并且 fullName
getter简单地返回
连接的 firstName
+ lastName
并且从不使用 fullName
变量, p>
这是根据苹果的官方文档。 向下滚动到您可以实现自定义访问器方法
I have class A
, which exposes a way of getting and setting an object of type Foo
. In property parlance, I generally declare this in the interface:
@property (nonatomic, strong) Foo * foo;
This (in modern ObjC) generates both the accessors and an ivar, _foo
for storage.
If I want to do custom work in the accessors, I can implement one or both of them myself. But what if I not only want to do custom work, I actually don't want the ivar? In other words, I'm doing something else with the Foo object, like handing it back and forth to another internal object that I'm composed with. I don't actually need to keep storage for foo
in the instance of A
at all.
It seems like I have two choices:
- Declare the property, implement both accessors, and simply ignore the fact that the compiler creates storage for
_foo
, and never use it. - Declare my accessors explicitly:
- (Foo *)foo
and- (void)setFoo:(Foo *)foo
in the interface, like I used to in pre-modern ObjC.
The first seems inelegant at runtime, and the second seems inelegant in the declaration (where I'd probably now have a mix of properties and property-like accessors).
Is there a way to declare a property and have it serve as purely a declaration?
If you override both the setter and getter and don't use the variable within the setter and getter, a variable will not be created.
For example, if you have a class for which you want a firstName
and lastName
property, but perhaps also a setter
and getter
for a fullName
property, if your fullName
setter simply parses a string into firstName
and lastName
and sets these properties to that (and never stores the full string into a fullName
variable), and your fullName
getter simply returns
the concatenated firstName
+ lastName
and never uses a fullName
variable, one will never be created.
This is according to Apple's official documentation. Scroll down to "You Can Implement Custom Accessor Methods"
这篇关于如何声明一个@property,但是阻止它的ivar被创建?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!