开发者

Best way to initialise / clear a string variable cocoa

开发者 https://www.devze.com 2023-01-01 10:33 出处:网络
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 &am

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];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号