Why does delegate use weak references?

Source: Internet
Author: User

For example, set the delegate of B to A on the page, //. in m, B * B = [B alloc] init]; B. delegate = self; [self. view addSubview: B]; [B release]; then 1. A is responsible for creating B, and A's lifecycle must be longer than B (B exists, A must also exist; A exists, B may not exist) that is to say in B (instance B) when A (Instance) exists, so there is no need to use retain to count the reference + 1, assign is enough to 2. let's take A look at the following situation: If A crashes before B (the instance of a is first destroyed by release), then of course the method in a is not called by B after [A relase, however, when using retain, A is still not destroyed, so the method in A will still be called by B, but assgin does not have this problem 3. in essence, delegate is a pointer (assuming: ccPoint) pointing to a class that exists before it. We use del The egate Pointer Points to the existing pointer (ccPoint). Then, through delegate, that is, ccPoint, you can access the instance method in CCClass 4. avoid retain cycle, that is, there are two objects A and B, there is an instance variable of B in A, and there is another instance variable of A in B. to release A, you must releaseA B, to release B, there must be A in release B. In this way, A Retain Circle is generated, and a B cannot be dealloc. the Method to Solve Retain Circle is to use weak reference. The weak reference does not have the ownership of the referenced Object, so it does not need to be release, thus solving the Retain Circle problem. to prevent the occurrence of Retain Circle, delegate is usually weakly referenced. Therefore, we generally do not need to regrade a delegate. NSURLConnection is an exception.

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.