Objective-C 中强弱的区别 [英] Differences between strong and weak in Objective-C

查看:26
本文介绍了Objective-C 中强弱的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Obj-C 的新手,所以我的第一个问题是:

I'm new to Obj-C, so my first question is:

@property 对象指针声明中的 strongweak 有什么区别?

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:

  1. 委托属性,这些属性经常被弱引用以避免保留循环,以及

  1. 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.

atomic vs. nonatomic 指的是编译器为属性合成的 getter 和 setter 方法的线程安全性.atomic(默认值)告诉编译器使访问器方法成为线程安全的(通过在访问 ivar 之前添加锁),而 nonatomic 则相反.nonatomic 的优点是性能略高.在 iOS 上,Apple 的几乎所有属性都使用 nonatomic,因此一般建议您也这样做.

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 中强弱的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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