例1.
先看个可变字符串与不可变字符串的例子:
NSMutableString *mutableStr = [NSMutableString stringWithString:@"jack"];
NSString *name = mutableStr;
NSLog(@"name = %@", name);
[mutableStr appendString:@" and rose"];
NSLog(@"name = %@", name);
mutableStr = nil;
NSLog(@"name = %@", name);
输出:
2020-08-14 09:52:25.021500+0800 [61167:1662404] name = jack
2020-08-14 09:52:25.021599+0800 [61167:1662404] name = jack and rose
2020-08-14 09:52:25.021677+0800 [61167:1662404] name = jack and rose
将
mutableStr
赋值给name
,此时name
也就是可变字符串,故改变mutableStr
的值name
也会改变。注意mutableStr = nil
是将mutableStr
指针中保存的堆内存地址变为nil
,并不是把堆内存地址的值变为nil
,所以最后一行输出name
依旧为jack and rose
。
例2.
再看可变类型在block中
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@"1",@"2", nil];
void(^block)(void) = ^{
NSLog(@"block1 - %@",arr);
[arr addObject:@"5"];
NSLog(@"block2 - %@",arr);
};
[arr addObject:@"3"];
[arr addObject:@"4"];
arr = nil;
block();
先想下输出会是什么:
~
~
~
~
~
~
~
~
~
~
~
~
2020-08-14 10:24:26.403654+0800 [61959:1683035] block1 - (
1,
2,
3,
4
)
2020-08-14 10:24:26.403781+0800 [61959:1683035] block2 - (
1,
2,
3,
4,
5
)
由于是可变类型,在block外更改
arr
的内容是可以影响到block内的arr
(反之亦然),但是arr = nil
是不会将block内的arr
置空,理由同例1。