在 NSString NSString Class Reference这是什么意思
Distributed objects:
Over distributed-object connections, mutable string objects are passed by-reference and immutable string objects are passed by-copy.
而且 NSString 无法更改,所以当我在这段代码中更改 str
时会发生什么
NSString *str = @"";
for (int i=0; i<1000; i++) {
str = [str stringByAppendingFormat:@"%d", i];
}
我会发生内存泄漏吗?或者什么?
最佳答案
您的代码在做什么:
NSString *str = @""; // pointer str points at memory address 123 for example
for (int i=0; i<1000; i++) {
// now you don't change the value to which the pointer str points
// instead you create a new string located at address, lets say, 900 and let the pointer str know to point at address 900 instead of 123
str = [str stringByAppendingFormat:@"%d", i]; // this method creates a new string and returns a pointer to the new string!
// you can't do this because str is immutable
// [str appendString:@"mmmm"];
}
Mutable 意味着你可以改变 NSString。例如使用 appendString。
pass by copy 意味着你得到一个NSString的副本,你可以做任何你想做的事情;它不会改变原来的 NSString
- (void)magic:(NSString *)string
{
string = @"LOL";
NSLog(@"%@", string);
}
// somewhere in your code
NSString *s = @"Hello";
NSLog(@"%@", s); // prints hello
[self magic:s]; // prints LOL
NSLog(@"%@", s); // prints hello not lol
但是想象一下你得到了一个可变的 NSString。
- (void)magic2:(NSMutableString *)string
{
[string appendString:@".COM"];
}
// somewhere in your code
NSString *s = @"Hello";
NSMutableString *m = [s mutableCopy];
NSLog(@"%@", m); // prints hello
[self magic2:m];
NSLog(@"%@", m); // prints hello.COM
因为您传递了一个引用,您实际上可以更改字符串对象的“值”,因为您使用的是原始版本而不是副本。
注意
只要您的应用程序存在,字符串文字就会存在。在您的示例中,这意味着您的 NSString *str = @"";
永远不会被释放。所以最后在你循环完你的 for 循环之后,你的内存中有两个字符串对象。它的 @""
您无法再访问它,因为您没有指向它的指针,但它仍然存在!而你的新字符串 str=123456....1000;但这不是内存泄漏。
关于ios - 需要有关 NSString 的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29691205/