如何将字符串附加到NSMutableString

时间:2012-02-07 17:14:25

标签: ios objective-c iphone

我是Objective-c的绝对新手

使用此代码

NSMutableString *teststring;
[teststring appendString:@"hey"];
NSLog(teststring);

控制台中没有显示任何内容。

当然我在这里做错了......: - )

5 个答案:

答案 0 :(得分:49)

您需要先创建字符串。

NSMutableString *teststring = [[NSMutableString alloc]init];

[teststring appendString:@"hey"];

NSLog(teststring);

现在,它将打印出来。

答案 1 :(得分:25)

将第一行更改为

NSMutableString *teststring = [NSMutableString string];

答案 2 :(得分:9)

这一行

NSMutableString *teststring;

只是建立一个指针,但不会创建任何东西。相反,您需要创建NSMutableString的新实例,例如:

NSMutableString *teststring = [[NSMutableString alloc] init];
[teststring appendString:@"hey"];
NSLog("%@", teststring);

答案 3 :(得分:4)

样品:

NSMutableString *buffer = [[NSMutableString alloc] init]; // retain count = 1. Because of the "alloc", you have to call a release later

[buffer appendString:@"abc"];
NSLog(@"1 : %@", buffer);
[buffer appendString:@"def"];
NSLog(@"2 : %@", buffer);

[buffer release]; // retain count = 0 => delete object from memory

答案 4 :(得分:0)

NSMutableString *tag = [NSMutableString stringWithString: @"hello <td> this is inside td </td> 000999 <><> ..<. ><> 00000 <td>uuuuu</td> vvvvv <td> this is also inside td </td>"];  
    NSRange open = [tag rangeOfString:@"<"]; 
    while(open.location != NSNotFound) 
    {
        NSRange close = [tag rangeOfString:@">"]; 
        NSRange string = NSMakeRange(open.location, close.location-open.location+1);
        [tag replaceCharactersInRange:string withString:@""];               
        open =  [tag rangeOfString:@"<"];
        NSLog(@"%@",tag);
    }