iOS nsstring type why copy decoration

Source: Internet
Author: User

In the process of development, only know the NSString type is best to use copy decoration and can not use strong, but do not know why, today understand the next, finally understand.

As shown below, when the modifier is copy, because Nsmutablestring is a subclass of the NSString type, So you can use pointer self.name to point to MSTR, but we know that the meaning of copy refers to the deep copy of the new object when the value is re-assigned to Self.name.

So at this point self.name pointer and MSTR pointer to the object is different, so when the Mstr object to send the method appendstring, the change is only MSTR (this time the value becomes mutablestring----addstring), and Self.name still does not Change (mutablestring----), whereas the modifier is strong, because strong means that the pointer points to the original object, and the reference count + 1, so self.name and Mstr point to the same object, and self.name changes together when MSTR is modified. Therefore, in order to avoid the value of the NSString type being modified, it is generally recommended to modify it with the copy modifier.

@interface*name; // @property (Nonatomic,strong) nsstring *name; @end
- (void) viewdidload {[Super viewdidload]; Nsmutablestring*MSTR = [Nsmutablestring stringWithFormat:@"mutablestring----"]; Self.name=MSTR; [MSTR appendString:@"addstriing"];//when the modifier for name is copy, the result of name is mutablestring----NSLog (@"%@", MSTR);//when the modifier for name is strong, the result of name is mutablestring----addstriingNSLog (@"%@", Self.name);}

iOS nsstring type why copy decoration

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.