2014-02-24 53 views
3

我想讓我的字符串:@「測試」 @「----」stringByAppendingString在for循環

在控制檯我得到:「對象返回空描述」

我儘量讓對於foo中的每一個字符,在foo2中都有一個「 - 」,這樣我得到:「----」,但它不起作用。我看了看,發現首先初始化我的字符串,但是我用tho做:@「」還是我錯了?但它也不會因[NSString new]而褪色。

問題在哪裏?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSString *foo = @"test"; 
    NSString *foo2 = @""; 

    for(int i=0; i < foo.count; i++) 
    { 
     [foo2 stringByAppendingString:@"-"]; 
    } 

    NSLog(foo2); 
} 

回答

5

變化

for(int i=0; i < foo.count; i++) 
{ 
    [foo2 stringByAppendingString:@"-"]; 
} 

for(int i=0; i < foo.length; i++) 
{ 
    foo2 = [foo2 stringByAppendingString:@"-"]; 
} 
+0

感謝,但它始終是相同的... – Sam

+0

我剛纔檢查,一切正常!如果foo == @「test」,那麼foo2 == @「----」。它應該以這種方式工作嗎? – Avt

+0

哦......你是對的:)我忽視了'foo2 =',但它真的很棒! THNAK YOU !! – Sam

1

始終使用NSLog(@"%@", object)否則,你會得到編譯器錯誤 - > 「存在安全隱患」

對於字符串操作考慮的NSMutableString。

相同的代碼可以用的NSMutableString寫成,

NSMutableString *foo2 = [[NSMutableString alloc] initWithFormat:@""]; 
for(int i=0; i < [foo length] ; i++){ 
    [foo2 appendString:@"-"]; 
} 
NSLog(@"%@", foo2); 
+0

謝謝,但它總是相同的... – Sam

+0

你能否闡述你的觀點? – Arvchz