Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

memory management - Swift delegation - when to use weak pointer on delegate

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...