简体   繁体   English

使用弱点有什么好处?什么时候可以使用弱点?

[英]What is the benefits of using weak points or when can we use weak points?

Today I read book about ARC. 今天,我读了有关ARC的书。 So there are two type points both strong and weak points. 因此,存在两个优点和缺点。 I already searched the property about them and got it. 我已经搜索了关于他们的财产并获得了它。 But I couldn't see or understand why we use weak point instead of strong? 但是我看不到或不明白为什么我们使用弱点而不是强点? This is simple question. 这是一个简单的问题。 Please let me know easily. 请让我轻松知道。

Thanks. 谢谢。

First of all its not weak points, its weak property. 首先,它不是弱点,是其弱点。 Lets say if you don't want owner ship of a particular object you can use weak property. 可以说,如果您不希望某个特定对象成为所有者,则可以使用弱属性。 If the actual owner of this reference release this and its retain count becomes zero, a weak reference will be automatically assigned to nil. 如果该引用的实际所有者释放了该引用,并且其保留计数变为零,则弱引用将自动分配为nil。 Which will save you from crashes. 这样可以避免崩溃。

You can get more information here : https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html 您可以在此处获取更多信息: https : //developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html

This question has been answered very well on apple's page ! 这个问题在苹果页面上得到了很好的回答! I will just link it in hope it really helped you to get the required info ! 我将其链接起来,希望它确实可以帮助您获取所需的信息!

link is here :) arc 链接在这里:)

also I think this SO question is very helpful for understanding the things :[link]here ( Objective-C ARC: strong vs retain and weak vs assign ) 我也认为这个SO问题对于理解事物非常有帮助:[link]在此( Objective-C ARC:强vs保留,弱vs分配

To be simple, you use "weak property" and or "weak variable" for following: 简单来说,您可以使用“弱属性”和/或“弱变量”进行以下操作:

  1. You do not want to take the ownership of object. 您不想获取对象的所有权。 Like delegate/dataSource are generally declared weak. 像委托/数据源一般被声明为弱。
  2. You may say you can also use "assign" instead of "weak". 您可能会说,也可以使用“分配”代替“弱”。 When the variable is freed from memory, using "weak" automatically sets it to nil, whereas "assign" now is referring to deallocated instance and code can crash if you try to do something on it. 当变量从内存中释放后,使用“弱”将其自动设置为nil,而“分配”现在指的是释放实例,并且如果您尝试对其进行处理,代码可能会崩溃。
  3. To avoid retain cycles causing memory leaks. 为了避免保留周期导致内存泄漏。 For example avoid passing "self" in blocks. 例如,避免在块中传递“自我”。 use "__weak id weakSelf = self", and now pass weakSelf in blocks. 使用“ __weak id weakSelf = self”,现在以块形式传递weakSelf。

ARC is your friend, but can do potential harm if not taken care of things mentioned above. ARC是您的朋友,但是如果不注意上面提到的事情,可能会造成潜在的伤害。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM