初始化/清除字符串变量可可的最佳方法 [英] Best way to initialise / clear a string variable cocoa
问题描述
我有一个例程,可以通过循环解析文本.在每条记录的末尾,我需要清除我的字符串变量,但我读到someString = @"实际上只是指向新的字符串&导致内存泄漏.
I have a routine that parses text via a loop. At the end of each record I need to clear my string variables but I read that someString = @"" actually just points to a new string & causes a memory leak.
处理此问题的最佳方法是什么?我应该在迭代之间使用可变字符串vars还是使用setString:@"吗?
What is the best way to handle this? Should I rather use mutable string vars and use setString:@"" between iterations?
推荐答案
在这种情况下,必须小心创建NSString :(工厂方法)或(分配init或(使用@").)
You have to be careful in which case you create the NSString: (factory method) or (alloc init or (using @"").
If you use @"", it is a constant string, see here: Constant NSString
如果使用[[NSString alloc] init],则需要将其释放.只需执行[someString release].
If you use [[NSString alloc] init], you need to release it.You just need to do [someString release].
如果您使用[NSString stringWithFormat:@"]之类的内容,则无需发布它,因为它已在运行时自动发布
If you use something like [NSString stringWithFormat:@""], you don't need to release it because it is already auto released by runtime
这篇关于初始化/清除字符串变量可可的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!