iOS promotion path-strong and weak references

Source: Internet
Author: User

In the Objective-c arc mode, see the following code

ID OBJC =[[nsobject Alloc]init];

Here the ID is strongly referenced by default

In the case of a strong reference, there are times when a circular reference is required, and weak is needed to help.

int main (int argc, const char * argv[]) {

ID __weak obj0 = nil;

@autoreleasepool {

if (YES) {

ID obj1 = [[NSObject alloc]init];

Obj0 = obj1;

NSLog (@ "%@", obj0);

}

NSLog (@ "%@", obj0);

}

return 0;

}

Printing results:

2015-09-01 15:30:25.640 Strong Reference Testing [2166:153376] <NSObject:0x100211f20>

2015-09-01 15:30:25.642 Strong Reference Testing [2166:153376] (NULL)

因为obj1生成的默认的为强引用(__strong),在超出if的作用域之后,obj1所持有的对象被释放, obj0为弱引用,所以obj0不持有对象,在obj1对象释放后,obj0自动的被赋值为nil 弱引用的特性是,不持有对象,即便是写成id __weak obj1 = [[NSObject alloc] init]; 此代码系统会给与警告,因为这里obj1被声明成弱引用,那么在赋值之后,alloc出来的对象会被立即释放。

iOS promotion path-strong and weak references

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.