Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在iPhone上正确重用NSMutableString_Iphone_Objective C_Memory Management_Nsmutablestring_Stringwithformat - Fatal编程技术网

在iPhone上正确重用NSMutableString

在iPhone上正确重用NSMutableString,iphone,objective-c,memory-management,nsmutablestring,stringwithformat,Iphone,Objective C,Memory Management,Nsmutablestring,Stringwithformat,在iPhone上使用objective-c,这段代码有什么问题? 是内存泄漏吗?为什么? 如何正确地执行此操作 NSMutableString *result = [NSMutableString stringWithFormat:@"the value is %d", i]; 。。。然后在我的代码后面。。。我可能需要将此更改为: result = [NSMutableString stringWithFormat:@"the value is now %d", i]; 我需要第二次使用st

在iPhone上使用objective-c,这段代码有什么问题? 是内存泄漏吗?为什么? 如何正确地执行此操作

NSMutableString *result = [NSMutableString stringWithFormat:@"the value is %d", i];
。。。然后在我的代码后面。。。我可能需要将此更改为:

result = [NSMutableString stringWithFormat:@"the value is now %d", i];

我需要第二次使用stringWithFormat。。。但是这不是在创建一个新字符串而没有正确释放旧字符串吗?

不,它不会泄漏内存,因为
stringWithFormat:
返回一个自动释放的对象。

不,它不会泄漏内存,因为
stringWithFormat:
返回一个自动释放的对象。

您可以使用实例方法“setString”对于已经存在的NSMutableString,如下所示:

[ result setString:[NSString stringWithFormat:@"the value is now %d", i] ];

您可以对已经存在的NSMutableString使用实例方法“setString”,如下所示:

[ result setString:[NSString stringWithFormat:@"the value is now %d", i] ];

如果您真的想重用字符串,可以使用

[result setString:@""];
[result appendFormat:@"the value is now %d", i];
但是,除非您注意到性能/内存问题,否则只需使用

NSString *result = [NSString stringWithFormat:@"the value is %d", i];

/* ... */

result = [NSString stringWithFormat:@"the value is now %d", i];

一般来说,处理不可变对象更容易,因为它们在你脚下无法改变。

如果你真的想重用字符串,你可以使用

[result setString:@""];
[result appendFormat:@"the value is now %d", i];
但是,除非您注意到性能/内存问题,否则只需使用

NSString *result = [NSString stringWithFormat:@"the value is %d", i];

/* ... */

result = [NSString stringWithFormat:@"the value is now %d", i];

一般来说,处理不可变对象比较容易,因为它们在你脚下是无法改变的。

在我看来,你拥有的东西是用新内容替换可变字符串的自然方式,除非你在其他地方对同一可变字符串有其他引用

如果您没有对它的其他引用,并且重用字符串只是为了提高性能/内存占用,那么这听起来像是过早的优化


顺便说一句,您不拥有通过stringWithFormat获得的字符串:因此您不需要(确实不能)释放它。

在我看来,您拥有的是用新内容替换可变字符串的自然方式,除非您在其他地方对同一可变字符串有其他引用

如果您没有对它的其他引用,并且重用字符串只是为了提高性能/内存占用,那么这听起来像是过早的优化


顺便说一句,您不拥有通过stringWithFormat获得的字符串:因此您不需要(确实不能)释放它。

假设您的意思是
[NSString stringWithFormat
,它完全忽略了这一点:它创建一个新字符串,然后将其内容复制到可变字符串,而不是简单地重用可变字符串的内存。假设您的意思是
[NSString stringWithFormat
,它完全没有抓住要点:它创建一个新字符串,然后将其内容复制到可变字符串,而不是简单地重用可变字符串的内存。