Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C copy and retain

When should I use copy instead of using retain? I didn't quite get it.

like image 458
Samuli Lehtonen Avatar asked Jun 22 '11 14:06

Samuli Lehtonen


People also ask

What is a difference between copy and retain?

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.

Does copy increase retain count?

No, a copied object will have a retain count of 1, just like a newly initialized object.

What is difference between assign and retain?

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.

What is copy Objective C?

copy -- It creates a new object and when new object is created retain count will be 1.


1 Answers

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.

like image 90
Joshua Weinberg Avatar answered Sep 19 '22 23:09

Joshua Weinberg