@property 在 Objective-C 中保留、分配、复制、非原子性 [英] @property retain, assign, copy, nonatomic in Objective-C

查看:20
本文介绍了@property 在 Objective-C 中保留、分配、复制、非原子性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为 Objective-C 的新手,有人能给我一个关于保留、分配、复制和我遗漏的任何其他东西的概述,遵循@property 指令吗?他们在做什么,为什么我要使用一个而不是另一个?

As someone that's new to Objective-C can someone give me an overview of the retain, assign, copy and any others I'm missing, that follow the @property directive? What are they doing and why would I want to use one over another?

推荐答案

MrMage 链接的文章不再有效.所以,这是我在 Objective-C 的(非常)短时间编码中学到的东西:

The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:

非原子与原子- 原子"是默认值.始终使用非原子".我不知道为什么,但我读过的书说很少有理由"使用原子".(顺便说一句:我读的书是 BNR 《iOS 编程》一书.)

nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)

读写与只读- 读写"是默认值.当您@synthesize 时,将为您创建一个 getter 和一个 setter.如果您使用只读",则不会创建任何 setter.将它用于在对象实例化后您不想更改的值.

readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.

保留与复制与分配

  • 分配"是默认值.在由@synthesize 创建的 setter 中,值将简单地分配给属性.我的理解是assign"应该用于非指针属性.
  • 当属性是指向对象的指针时需要retain".@synthesize 生成的 setter 将保留(也就是添加保留计数)对象.完成后,您需要释放该对象.
  • 当对象可变时需要copy".如果您需要对象此时的值,并且您不希望该值反映该对象的其他所有者所做的任何更改,请使用此选项.完成后您需要释放对象,因为您保留了副本.

这篇关于@property 在 Objective-C 中保留、分配、复制、非原子性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆