gpt4 book ai didi

ios - 需要有关 Objective-c 属性概念的帮助

转载 作者:可可西里 更新时间:2023-11-01 04:35:51 24 4
gpt4 key购买 nike

我正在阅读 Apple Doc用于理解属性实例变量但有点困惑

来自 Apple 文档:

Most Properties Are Backed by Instance Variables By default, a readwrite property will be backed by an instance variable, which will again be synthesized automatically by the compiler.

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc), and freed when the object is deallocated.

Unless you specify otherwise, the synthesized instance variable has the same name as the property, but with an underscore prefix. For a property called firstName, for example, the synthesized instance variable will be called _firstName.

Although it’s best practice for an object to access its own properties using accessor methods or dot syntax, it’s possible to access the instance variable directly from any of the instance methods in a class implementation. The underscore prefix makes it clear that you’re accessing an instance variable rather than, for example, a local variable:

如果使用访问器方法或点语法是最佳实践,那么为什么要使用 _ivarPropertyName?

为什么要使用ivar 来表示属性?它有什么好处?当苹果说“使用访问器方法或点语法是最佳实践”时

最佳答案

@property声明属性的存在(描述其接口(interface)),但不指定该属性的实现。但是属性需要将它们的内容存储在某处。默认情况下,编译器会为此合成一个 ivar(以及匹配的 setter 和 getter)。所以通常你可以忽略 ivar 的存在而只使用 点语法

我遵循 Apple 的建议并尽量避免直接使用 ivars。但有时您希望在不调用其 getter 的情况下访问属性。我的代码中最常见的异常是延迟初始化的只读属性:

@interface MyObject : NSObject
@property ( nonatomic, readonly ) id someProperty ;
@end

@implementation MyObject
@synthesize someProperty = _someProperty ; // required; compiler will not auto-synthesize ivars for readonly properties

-(id)someProperty
{
if ( !_someProperty )
{
_someProperty = ... create property here
}

return _someProperty ;
}

@end

此外,您可能不想为 -dealloc 中的属性调用 getter方法...例如,计时器属性。避免在 -dealloc 中创建计时器, 直接访问ivar:

-(void)dealloc
{
[ _myTimer invalidate ] ; // don't use self.myTimer here, that would create a timer even though we're going away...
}

可能还有更多用例。对于大多数属性,您甚至不需要使用 ivar,只需使用 <value> = self.propertyself.property = <new value> .

编辑:

此外,与直接访问 ivar 相比,通过消息分发(使用点访问器语法 或 getter)访问属性会有一些额外的开销,但它在几乎所有情况下都没有区别。

关于ios - 需要有关 Objective-c 属性概念的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15493882/

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