Differences between strong and weak in Objective-C(Objective-C中强弱的区别)
问题描述
我是 Obj-C 的新手,所以我的第一个问题是:
I'm new to Obj-C, so my first question is:
@property
对象指针声明中的strong
和weak
有什么区别?
What are the differences between strong
and weak
in @property
declarations of pointers to objects?
另外,nonatomic
是什么意思?
推荐答案
强引用(在大多数情况下都会用到)意味着你想拥有"你用这个属性/变量引用的对象.只要您使用强引用指向它,编译器就会注意您分配给此属性的任何对象都不会被破坏.只有将属性设置为 nil
后,对象才会被销毁(除非一个或多个其他对象也持有对它的强引用).
A strong reference (which you will use in most cases) means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil
will the object get destroyed (unless one or more other objects also hold a strong reference to it).
相反,使用弱引用表示您不想控制对象的生命周期.您弱引用的对象仅存在,因为至少有一个其他对象持有对它的强引用.一旦不再是这种情况,对象就会被销毁,并且你的弱属性将自动设置为 nil
.iOS 中最常见的弱引用用例是:
In contrast, with a weak reference you signify that you don't want to have control over the object's lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil
. The most frequent use cases of weak references in iOS are:
委托属性,通常被弱引用以避免保留循环,以及
delegate properties, which are often referenced weakly to avoid retain cycles, and
视图控制器的主视图的子视图/控件,因为这些视图已经被主视图强占.
subviews/controls of a view controller's main view because those views are already strongly held by the main view.
原子与非原子是指编译器为属性综合的 getter 和 setter 方法的线程安全性.atomic(默认)告诉编译器使访问器方法线程安全(通过在访问 ivar 之前添加锁),而 nonatomic 则相反.非原子的优点是性能稍高.在 iOS 上,Apple 对其几乎所有属性都使用非原子,因此一般建议您也这样做.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance. On iOS, Apple uses nonatomic for almost all their properties so the general advice is for you to do the same.
这篇关于Objective-C中强弱的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Objective-C中强弱的区别
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01