2012-02-07 63 views
16

我是一個絕對的新手用Objective-C的如何將字符串追加到的NSMutableString

與此代碼

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

沒有東西顯示在控制檯中。

我肯定做錯了這裏... :-)

回答

23

更改第一行

NSMutableString *teststring = [NSMutableString string]; 
46

您需要首先創建的字符串。

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

[teststring appendString:@"hey"]; 

NSLog(teststring); 

現在,它將打印。

+0

謝謝,這個合身我。 – 2014-02-11 16:21:51

9

此行

NSMutableString *teststring; 

只是建立了一個指針,但不會創建任何東西。相反,你需要創建的NSMutableString一個新的實例,例如:

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

樣品:

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 
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); 
    }