Best way to initialise / clear a string variable cocoa

余生颓废 提交于 2019-12-11 02:02:41

问题


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.

What is the best way to handle this? Should I rather use mutable string vars and use setString:@"" between iterations?


回答1:


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

If you use [[NSString alloc] init], you need to release it.You just need to do [someString release].

If you use something like [NSString stringWithFormat:@""], you don't need to release it because it is already auto released by runtime




回答2:


Since NSStrings are immutable, you cannot change the contents of the string. And by initializing it with @"" you're actually creating a constant NSString object.

You can either work with a NSString local to the loop, and release it in the end of the loop - or you can use a NSMutableString instead. I would prefer the loop local string though.

for ( ; ;) {
    NSString* str = [[NSString alloc] initWithFormat:@"%@", CONTENT];
    ...
    [str release];
}


来源:https://stackoverflow.com/questions/2922196/best-way-to-initialise-clear-a-string-variable-cocoa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!