Swift: About delegate and swiftdelegate

Source: Internet
Author: User

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'sprotocolYes.classFor other typesstructOrenumThis type does not manage the memory by referencing the count, so it cannot be used.weakThis 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@objcThe 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.classThis can explicitly indicate for the compiler that this protocol can only be composedclassTo achieve:

 

 

Add@objcThe 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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.