Swift授权 - 何时使用弱指针代理 [英] Swift delegation - when to use weak pointer on delegate
问题描述
我的理解是,如果您使用未定义为类的协议,则无法将其委托指针分配给弱。
协议MyStructProtocol {
// whatever
}
struct MyStruct {
var代理:MyStructProtocol?
}
但是,当您的协议定义为类类型协议时,您需要将您的代理设置为弱指针?
协议MyClassProtocol:Class {
// whatever
}
class MyClass {
weak var delegate:MyClassProtocol?
}
我是正确的吗?在苹果的快速指南中,类协议示例不使用弱分配,但在我的测试中,如果我的代理不被弱引用,我看到很强的引用周期。
struct
类型,但是,参考循环的强大风险大大降低,因为 struct
类型不是引用类型,所以创建强大的参考循环更困难。但是,如果委托对象是一个类对象,那么你可能希望使协议成为一个类协议,使其变弱。
在我看来,让代表弱的是只能部分缓解强参考周期的风险。这真的是一个所有权的问题。大多数委托协议是这样的情况,即所涉及的对象没有商业权利要求对代理人拥有所有权,而只是所涉及的对象提供向委托人通知某事(或请求某些内容)的能力。
Can someone explain when and when not to use a 'weak' assignment to a delegate pointer in Swift, and why?
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?
}
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.
You generally make class protocols (as defined with class
keyword) weak to avoid the risk of a "strong reference cycle" (formerly known as a "retain cycle"). Failure to make the delegate weak doesn't mean that you inherently have a strong reference cycle, but merely that you could have one.
With struct
types, though, the strong reference cycle risk is greatly diminished because struct
types are not "reference" types, so it's 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.
In my opinion, making class delegates weak is only partially to alleviate the risk of a strong reference cycle. It's really 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).
这篇关于Swift授权 - 何时使用弱指针代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!