When should I use copy instead of using retain? I didn't quite get it.
Retain increases the retain count of an object by 1 and takes ownership of an object. Whereas copy will copy the data present in the memory location and will assign it to the variable so in the case of copy you are first copying the data from a location assign it to the variable which increases the retain count.
No, a copied object will have a retain count of 1, just like a newly initialized object.
Assign creates a reference from one object to another without increasing the source's retain count. Retain creates a reference from one object to another and increases the retain count of the source object.
copy -- It creates a new object and when new object is created retain count will be 1.
You would use copy
when 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 3rd line there.
NSMutableString *mutString = [NSMutableString stringWithString:@"ABC"];
NSString *b = [mutString copy];
[mutString appendString:@"Test"];
In this case b is the original string, and isn't modified by the 3rd line.
This applies for all mutable types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With