Delegate
The interface-delegate (protocol-delegate) pattern in COCOA development is a common design pattern, which runs through the COCOA framework, and makes an indelible contribution to the relationship between the code and the cleaning and reconciliation.
In the ARC, for the general delegate, we will specify it as weak in the declaration, and it will be reset back to nil when the delegate actual object is released. This ensures that even if delegate does not exist, we will not crash because of access to reclaimed memory. This feature of ARC eliminates a very common crash error in COCOA development, saying it is not too much to save thousands of programmers.
We would certainly like to do so in Swift. But when we try to write code like this, the compiler won't let us through:
The code is as follows |
Copy Code |
protocol myclassdelegate { func method () } Class MyClass { weak var delega Te:myclassdelegate? } Class Viewcontroller:uiviewcontroller, myclassdelegate { //... var someinstance:myclass! override func Viewdidload () { super.viewdidload () someinstance = MyClass () someinstance.delegate = self } Func method () { & nbsp; print ("Do something") } //... } |
Weak var delegate:myclassdelegate? Compile error
' Weak ' cannot be applied to Non-class type ' myclassdelegate '
This is because Swift's protocol can be observed by other types other than class, and for types like struct or enums, which themselves do not manage memory by reference counting, it is not possible to decorate with the concept of arcs such as weak.
To use weak delegate in Swift, we need to limit protocol to class. One approach is to declare protocol as OBJECTIVE-C, which can be achieved by adding @objc keyword before protocol, OBJECTIVE-C protocol is only possible for classes, so it makes sense to use weak to modify it:
The code is as follows |
Copy Code |
@objc protocol Myclassdelegate { Func method () } |
Another possible better approach is to add class to the name of the Protocol declaration, which can explicitly indicate to the compiler that the protocol can only be implemented by class.
The code is as follows |
Copy Code |
Protocol Myclassdelegate:class { Func method () } |
Compared to adding @objc, the latter method can show the essence of the problem and avoid too much unnecessary objective-c compatibility, which can be said to be a better way to solve it.