首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >属性:"assign“vs "readonly”

属性:"assign“vs "readonly”
EN

Stack Overflow用户
提问于 2012-02-23 12:29:59
回答 4查看 2K关注 0票数 0

我在一些演示代码中看到了这一点:

@property (readonly) SomeObject* someInstance;

我所缺少的是没有提到赋值、复制或保留;如果省略,它是什么类型的指针?显然,它是某种类型的指针,但我认为在没有retaincopy的情况下,所有指针都将是assign,因为它们只是指向并等于someInstance

但我不想做这样的假设。我发现,属性看起来很容易理解,但实际上这个概念可能有点难理解。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-02-23 12:37:29

其他值(保留、复制、分配)仅在涉及setter时才重要。使用这些属性中的任何一个生成的任何getter都是相同的。保留、复制或赋值仅在设置值时才适用,因为您正在更改setter将对传入的对象执行的操作的行为。因为这个属性是只读的,这意味着你只需要创建一个getter来返回对象的指针,其他任何东西都不重要,因为你无论如何都不能设置它。

票数 3
EN

Stack Overflow用户

发布于 2012-02-23 12:38:02

代码语言:javascript
复制
**readonly**
Indicates that the property is read-only.
If you specify readonly, only a getter method is required in the @implementation block. If you use the @synthesize directive in the implementation block, only the getter method is synthesized. Moreover, if you attempt to assign a value using the dot syntax, you get a compiler error.

**assign**
Specifies that the setter uses simple assignment. This attribute is the default.
You use this attribute for scalar types such as NSInteger and CGRect.

readonly是可写入性之一。有2个,readwrite (默认)和readonly。

assign是设置器语义之一。如保留/复制等。

Apple Documentation

票数 2
EN

Stack Overflow用户

发布于 2012-02-23 12:37:57

如果不使用ARC,则assignretaincopy属性仅影响该属性的编译器生成的setter方法。因为编译器不会为readonly属性生成setter方法,所以您不需要指定这些属性中的任何一个。

如果您提供了用户可以用来设置属性的其他方法,以记录您对属性值的所有权(或不所有权),那么无论如何指定其中一个是很有用的。

如果使用的是ARC和@synthesize,则属性的所有权必须与实例变量的所有权相匹配。如果让编译器生成实例变量,它会自动将属性的所有权属性应用于实例变量。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9407185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档