Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C NSString Reference Types

Tags:

objective-c

I have a simple question. If I am declaring NSString (ref type) as shown below:

 NSString *johnsMoney = @"200";
    NSString *marysMoney = johnsMoney;

    NSLog(@"Johns Money %@",johnsMoney);
    NSLog(@"Marys Money %@",marysMoney);

    johnsMoney = @"100";
    NSLog(@"Johns Money %@",johnsMoney);
    NSLog(@"Marys Money %@",marysMoney);

The output produced is this:

 Johns Money 200
 Marys Money 200
 Johns Money 100
 Marys Money 200

From my understanding when I assign @"100" to johnsMoney should it not also change the value of "marysMoney" to 100 since marysMoney is pointing to johnsMoney.

UPDATE:

I believe the following example shows what I initially was trying to do:

Dog *dog1 = [[Dog alloc] init];
dog1.name = @"Dog 1";

Dog *dog2 = dog1;

NSLog(@"Dog 1 %@",dog1.name);
NSLog(@"Dog 2 %@",dog2.name);

dog1.name = @"Dog 3";

NSLog(@"Dog 1 %@",dog1.name);
NSLog(@"Dog 2 %@",dog2.name);
like image 448
john doe Avatar asked May 11 '26 13:05

john doe


1 Answers

johnsMoney and marysMoney are both pointers to strings.

When you write johnsMoney = @"100", it now points to a different string. This doesn't change marysMoney which still points to the original string.

If you were using NSMutableString, and you did [johnsMoney setString:@"100"], then it would change the underlying data (to which both variables would still be pointing).

like image 186
jtbandes Avatar answered May 13 '26 06:05

jtbandes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!