1

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?

Mohanad Kaleia
  • 793
  • 1
  • 9
  • 22
  • What specifically do you mean by "deleting the firstString"? And no, `mutableCopy` is not a deep copy. – rmaddy Apr 30 '15 at 14:47
  • For example in any part of app if I change the value of firstString, the secondString will get affect of that, Is there a way for deep copy? – Mohanad Kaleia Apr 30 '15 at 14:50
  • " in any part of app if I change the value of `firstString`..." So `firstString` is `NSMutableString` then, right? – Sergey Kalinichenko Apr 30 '15 at 14:51
  • If `firstString` is really an `NSMutableString` then changes to the value of the mutable string will be seen by both pointers. If `firstString` is really an `NSString` then you can change the value of `firstString` so it can't affect `secondString`. – rmaddy Apr 30 '15 at 14:52

2 Answers2

2

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

Azat
  • 6,745
  • 5
  • 31
  • 48
1

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