开发者

Append a NSString as the first line of another NSString

I have two NSString, A and B.

I would that A becomes B\nA.

How can I do?


If in a method I use

NSStrin开发者_运维问答g *string_B = [[NSString alloc] initWithString:@"something_from_a_DB"];
NSString *string_A = [[NSString alloc] initWithString:@"something_from_a_DB"];

if (aTrueCondition) {
   string_C = [NSString stringWithFormat:@"%@\n%@", string_B, string_A];
} else {
   string_C = string_A;
}

is string_C = string_A; a memory leak or is it good?


I added [string_A release], as string_C is a retained property. Now it works.


This is the way to put them together:

NSString *newString = [NSString stringWithFormat:@"%@\n%@", stringB, stringA];

The second part is “A becoming newString”. This is hard to do, as regular strings are immutable in Cocoa. The best thing you can do is throw out the old A and point A to the new string:

NSString *strA = @"foo";
NSString *strB = @"bar";
strA = [NSString stringWith…];

Just be careful not to leak A:

NSString *strA = [[NSString alloc] initWithString:@"foo"];
strA = [NSString stringWith…]; // this is a leak


NSString *str=[NSString stringWithFormat:@"%@\n%@",B,A];

use this.


NSString *stringA = [NSString stringWithFormat:@"%@\n%@", stringB, stringA];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜