<分区>
<分区>
我认为下面第二个例子的结果应该是“null”,但是我运行代码后发现,在例子1中输出的是“Strong-String”,而在例子2中是“null”
我真的不明白这是为什么。
例子:
// property definition
@property (nonatomic, strong) NSString *strongStr;
@property (nonatomic, weak) NSString *weakString;
// Sample 1
self.strongStr = @"Strong-String";
self.weakString = self.strongStr;
self.strongStr = nil;
// output -> Strong-String
NSLog(@"waekstring = %@", self.weakString);
// Sample 2
self.strongStr = [[NSString alloc] initWithUTF8String:"Strong-String"];
self.weakString = self.strongStr;
self.strongStr = nil;
// output -> null
NSLog(@"waekstring = %@", self.weakString);
最佳答案
当你定义一个字符串时
// Sample 1
self.strongStr = @"Strong-String";
编译器实际上保留了对该字符串的静态引用,如果您要创建另一个具有相同字符的字符串,您会注意到两个字符串的内存地址是相同的。编译器这样做是为了在反复使用同一字符串时帮助节省内存,这样就不必每次都重新分配内存。这就是为什么字符串没有被释放,而手动分配/初始化的字符串却被释放的原因
关于ios - 为什么这个硬编码的字符串没有被释放,而 alloc/inited 的字符串呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713257/