Best way to initialise / clear a string variable cocoa
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?
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
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];
}
精彩评论