Swift 委托 - 何时在委托上使用弱指针 [英] Swift delegation - when to use weak pointer on delegate

查看:22
本文介绍了Swift 委托 - 何时在委托上使用弱指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下什么时候什么时候不对 Swift 中的委托指针使用弱"赋值,为什么?

Can someone explain when and when not to use a 'weak' assignment to a delegate pointer in Swift, and why?

我的理解是,如果您使用未定义为类的协议,则您不能也不想将委托指针分配给weak.

My understanding is that if you use a protocol that is not defined as a class you cannot, nor want to, assign your delegate pointer to weak.

protocol MyStructProtocol{
    //whatever
}

struct MyStruct {
    var delegate: MyStructProtocol?
}

但是,当您的协议被定义为类类型协议时,您确实希望将委托设置为弱指针吗?

However, when your protocol is defined as a class type protocol then you DO want to set your delegate to a weak pointer?

protocol MyClassProtocol: class{
    //whatever
}

class MyClass {
    weak var delegate: MyClassProtocol?
}

我说得对吗?在 Apple 的 swift 指南中,类协议示例没有使用弱分配,但在我的测试中,如果我的代表没有被弱引用,我会看到强引用循环.

Am I correct? In Apple's swift guide there class protocol examples aren't using weak assignments, but in my testing I'm seeing strong reference cycles if my delegates aren't weakly referenced.

推荐答案

你通常使类协议weak 以避免强引用循环"(以前称为保留循环")的风险).(注意,我们现在通过将 AnyObject 协议添加到协议的继承列表来实现这一点;请参阅 Class-Only Protocols;我们不再使用 class 关键字.)未能使委托 weak并不意味着你天生就有一个强大的参考循环,而只是你可以拥有一个.

You generally make class protocols weak to avoid the risk of a "strong reference cycle" (formerly known as a "retain cycle"). (Note, we now do that by adding the AnyObject protocol to a protocol’s inheritance list; see Class-Only Protocols; we do not use the class keyword anymore.) Failure to make the delegate weak does not mean that you inherently have a strong reference cycle, but merely that you could have one.

使用struct类型,强引用循环的风险大大降低,因为struct类型不是引用"类型,所以更难创建强引用循环.但是如果委托对象是一个类对象,那么您可能希望将协议设为类协议并使其变弱.

With struct types, though, the strong reference cycle risk is greatly diminished because struct types are not "reference" types, so it is harder to create strong reference cycle. But if the delegate object is a class object, then you might want to make the protocol a class protocol and make it weak.

在我看来,使类委托weak 只是部分地减轻了强引用循环的风险.这也是一个所有权的问题.大多数委托协议的情况是,所讨论的对象没有业务要求对委托的所有权,而只是在所讨论的对象提供通知委托某事(或请求某事)的能力的情况下.例如,如果您希望视图控制器具有某些文本字段委托方法,则文本字段无权声明对视图控制器的所有权.

In my opinion, making class delegates weak is only partially to alleviate the risk of a strong reference cycle. It also is a question of ownership. Most delegate protocols are situations where the object in question has no business claiming ownership over the delegate, but merely where the object in question is providing the ability to inform the delegate of something (or request something of it). E.g., if you want a view controller to have some text field delegate methods, the text field has no right to make a claim of ownership over the view controller.

这篇关于Swift 委托 - 何时在委托上使用弱指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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