IOS-strong and copy, iOS-strongcopy

Source: Internet
Author: User

IOS-strong and copy, iOS-strongcopy

Strong and copy are commonly used modifiers. When to use strong and copy, the previous Code will be used first (the following code is directly written in ViewController );

Define two arrays first

///strong@property (nonatomic,strong) NSArray *arraystrong;///copy@property (nonatomic,copy) NSArray *arraycopy;

ViewDidLoad Method

-(Void) viewDidLoad {[super viewDidLoad]; NSMutableArray * arrayMut = [NSMutableArray array]; // Add a string [arrayMut addObject: @ "xiaogui1"]; self. arraystrong = arrayMut; self. arraycopy = arrayMut; // Add another string [arrayMut addObject: @ "xiaogui2"]; NSLog (@ "arraystrong = % @ \ narraycopy % @", self. arraystrong, self. arraycopy );}

Print results

We can see that arraystrong has changed with the change of arrayMut, while arraycopy has not changed with the change of arrayMut. The reason is that when strong is used for modification, no new space is created during the assignment, the Pointer Points to the memory space of the same pointer. When using copy, a new memory space is created, instead of pointing to the same memory as arrayMut. However, there is another problem:

 

 

When I change self to underline _ to reference a variable:

-(Void) viewDidLoad {[super viewDidLoad]; NSMutableArray * arrayMut = [NSMutableArray array]; // Add a string [arrayMut addObject: @ "xiaogui1"]; /// change self to _ arraystrong = arrayMut; _ arraycopy = arrayMut; // Add another string [arrayMut addObject: @ "xiaogui2"]; NSLog (@ "arraystrong =%@ \ narraycopy % @", self. arraystrong, self. arraycopy );}

Print result:

This is because the get set method is called when self is referenced, that is, the difference between strong and copy is realized, and the direct use of _ does not execute the get set method, therefore, the values of the two arrays are the same. Therefore, it is better to use self in projects. In my opinion, please note that there are errors.

 

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.