简体   繁体   中英

Swap the address of two ObjectiveC objects

I have the code to swap the address of two NSString objects, but the output is completely unexpected. Can anyone explain why I can't swap the reference of two objects.

    NSString* spt1 = @"spt1";
    NSString* spt2 = @"spt2";

    NSLog(@"spt1=%p", &spt1);
    NSLog(@"spt2=%p", &spt2);

    NSString* stmp = spt1;
    spt1 = spt2;
    spt2 = stmp;

    NSLog(@"spt1=%p", &spt1);
    NSLog(@"spt2=%p", &spt2);

output:

spt1=0x7fff53f5d208
spt2=0x7fff53f5d200
swap: spt1=0x7fff53f5d208
swap: spt2=0x7fff53f5d200

No you did not (cannot) swap the address of objects.

The object always live in heap and cannot be moved. You can move the content, but not the object.

What you have done is swap the value of spt1 and spt2 . However, the address of spt1 and spt2 (ie &spt1 and &spt2 ) remains the same.

Try this code instead. You can see the values are swapped but not the addresses.

NSLog(@"spt1=%p, &spt1=%p", spt1, &spt1);
NSLog(@"spt2=%p, &spt2=%p", spt2, &spt2);

NSString* stmp = spt1;
spt1 = spt2;
spt2 = stmp;

NSLog(@"spt1=%p, &spt1=%p", spt1, &spt1);
NSLog(@"spt2=%p, &spt2=%p", spt2, &spt2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM