Objective-C copy and save

When should I use a copy instead of saving? I did not quite understand.

+8
source share
3 answers

You must use copy if you want to guarantee the state of the object.

 NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"]; NSString *b = [mutString retain]; [mutString appendString:@"Test"]; 

At this point, b was just messed up by the third line there.

 NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"]; NSString *b = [mutString copy]; [mutString appendString:@"Test"]; 

In this case, b is the original string and is not modified by the third string.

This applies to all mutable types.

+29
source

save . This is done on the created object and simply increases the reference count.

copy . It creates a new object and when a new object is created, the counter will be 1. I hope this helps you.

+7
source

Copying is useful when you do not want the resulting value to change without your knowledge. For example, if you have the NSString property, and you rely on this line, which does not change after setting it, you need to use a copy. Otherwise, someone might pass you the NSMutableString and change the value, which in turn will change the base value of your NSString . The same thing happens with NSArray and NSMutableArray , except that the copy in the array simply copies all the pointer references to the new array, but prevents the deletion and addition of entries.

+4
source

All Articles