Objective-C的强项和弱项之间的差异 [英] Differences between strong and weak in Objective-C

查看:88
本文介绍了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.

原子性与非原子性是指编译器为该属性综合的getter和setter方法的线程安全性.原子(默认)告诉编译器使访问器方法成为线程安全的(通过在访问ivar之前添加锁),而非原子的则相反.非原子的优点是性能略高.在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的强项和弱项之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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