Swift: About delegate and swiftdelegate
In Cocoa development, the interface-delegate (protocol-delegate) mode is a common design pattern that runs through the entire Cocoa framework, it makes an indelible contribution to clearing the relationship between codes and decoupling.
In ARC, for general delegate, We will specify it as weak in the declaration. When the actual delegate object is released, it will be reset back.nil
. This ensures that even if the delegate does not exist, we will not crash due to access to the recycled memory. This feature of ARC eliminates a very common crash error in Cocoa development, saying it is nothing to do to save thousands of programmers.
We certainly hope to do the same in Swift. But when we try to write such code, the compiler won't let us through:
This is because Swift'sprotocol
Yes.class
For other typesstruct
Orenum
This type does not manage the memory by referencing the count, so it cannot be used.weak
This concept of ARC is modified.
To use weak delegate in Swift, we need to limit protocol to class. One way is to declare protocol as Objective-C, which can be done by adding@objc
The protocol of Objective-C can only be implemented by classes. Therefore, it is reasonable to use weak to modify the protocol:
Another better way is to add the name after the name declared by protocol.class
This can explicitly indicate for the compiler that this protocol can only be composedclass
To achieve:
Add@objc
The latter method can better demonstrate the essence of the problem and avoid excessive unnecessary Objective-C compatibility. It can be said that it is a better solution.