What does Mutable Copy in Objective C do

4.4k Views Asked by At

In objective C, same to C++ language, if you assign object to object it will get its pointing address like this:

object1 = object2;

So changing in one of objects above will affect the other one.

Is this the same for MutableCopy? and what is the difference between copy and MutableCopy?

How to do deep copy?

2

There are 2 best solutions below

0
On

In Objective C there is different memory management model than in C++, so you cannot just delete firstString - you should remove all strong references to it. In that case you create strong reference. When you reassign secondString it will point to another object. So NSString is immutable.

Mutable copy creates another string object and you can mutate it

0
On

Yes, mutableCopy (and copy) is a deep copy.

see the following test code:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *string1 = @"string1";
    NSString *string2 = string1;

    NSLog(@"Test 1(%p, %p): String 1: %@; String 2: %@", string1, string2, string1, string2);

    string1 = nil;

    NSLog(@"Test 2(%p, %p): String 1: %@; String 2: %@", string1, string2, string1, string2);

    string1 = string2;

    NSLog(@"Test 3(%p, %p): String 1: %@; String 2: %@", string1, string2, string1, string2);

    string2 = [string1 mutableCopy];

    NSLog(@"Test 4(%p, %p): String 1: %@; String 2: %@", string1, string2, string1, string2);




}

It produces the following output. You can see the memory location is the same when string2 is assigned to string1. In test 4, after the mutableCopy, the memory location is changed.

2015-04-30 11:07:30.359 TestStuff[9425:2555886] Test 1(0x103021068, 0x103021068): String 1: string1; String 2: string1
2015-04-30 11:07:30.359 TestStuff[9425:2555886] Test 2(0x0, 0x103021068): String 1: (null); String 2: string1
2015-04-30 11:07:30.359 TestStuff[9425:2555886] Test 3(0x103021068, 0x103021068): String 1: string1; String 2: string1
2015-04-30 11:07:30.359 TestStuff[9425:2555886] Test 4(0x103021068, 0x7f9a23d71b30): String 1: string1; String 2: string1