iOS Automatic memory management ARC

Source: Internet
Author: User

Today, a BUG broke out in the company, leading to 5000+crash.

Roughly, the delegate in UIKit visited the already released interface, which is the use of wild pointers to cause crash.

Come back and demonstrate the discovery

@property (nonatomic, assign) id<mycelldelegate> Delegate;//1@property (nonatomic, weak) id<mycelldelegate > DELEGATE;//2

Most of the UIKit's delegate are statements like 1.

Because iOS doesn't have ARC before 5, it's written assign for compatibility.

So what's the difference between assign and weak?

__strong nsstring *yourstring = [[NSString alloc] initwithutf8string: "Your string"];__weak nsstring *mystring = YourStrin   G   yourstring = nil;  __unsafe_unretained nsstring *theirstring = myString; Now all the pointers are nil

Weak attribute, if the point of memory is released, then automatically points to nil;

So using weak is not a wild pointer.

and assign and unsafe_unretained, always point to a memory address, if the memory is released, you will become a wild pointer

As follows

__strong nsstring *yourstring = @ "Your String";   __weak nsstring *mystring = yourstring;  __unsafe_unretained nsstring *theirstring = myString;   yourstring = nil; Now the yourstring and mystring pointers are nil, and theirstring is not nil, but it is a wild pointer.

So when we use the delegate in UIKit, we want to avoid responding to delegate's VC, or View-like instances being released prematurely, resulting in crash

Our own delegate can be written directly into weak, which avoids circular references and does not produce wild pointers.

Ps:assign can only be used in the definition of a property, the definition of a variable could be used in a similar unsafe_unretained

That's all ...


iOS Automatic memory management ARC

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.