开发者

NSString stringByAppendingString memory issue

On objective-c with iPhone:

I want to make a append with strings, but can I use autorelease? Is this right?

NSString *str1 = [[NSString alloc] initWithString:@"STR1"];
NSString *str2 = [[NSString alloc] initWithString:@"STR2"];

NSString *s = [[str1 autorelease] stringByAppendingString:[str2 autorelease]];

will this remove the *str1 and *str2 memory?

And for example, if I have a method:

+(void) doSomething
{
    NSString *str1 = [[NSString alloc] initWithString:@"STR1"];
    NSString *str2 = [[NSString alloc] initWithString:@"STR2"];

    NSString *s = [[str1 autorelease] stringByAppendingString:[str2 autorelease]];
    [[NSCl开发者_运维问答assFromString(s) alloc] init];
}

should I dealloc the *s pointer???


The general rule is that if you call alloc you have to call release on that resource.

So for your first example, str1 and str2 will be removed from memory, however you're not following convention for your autoreleases. Instead add the autorelease to the allocation line:

NSString *str1 = [[[NSString alloc] initWithString:@"STR1"] autorelease];
NSString *str2 = [[[NSString alloc] initWithString:@"STR2"] autorelease];

For the second example, because you're not calling alloc for the stringByAppendingString method, you don't need to release s.

Read through the iPhone Memory Management guide. It is worth the up front investment, so that you don't have to deal with these issues down the road. After that, read through Akosma Software's blog post.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜