Search code examples
objective-ccopyretain

Objective-C copy and retain


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


Solution

  • 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.