2010-10-05 44 views
0

構建了一個iPhone應用程序,它在按下按鈕時爲隨標籤生成一個標籤。另一個arc4random問題

簡單,只是爲了學習新的技能。

它工作正常,但我把任何價值似乎並沒有限制生成的隨機數的價值。它總是9位數字。你可以看到,我在%符號後面加了5,但是它會生成9位數字。 什麼做錯了?

回答

6
  1. NSNumber是一個Objective-C對象,因此您應該使用%@來顯示它。 %d顯示一個9位數字,因爲那是NSNumber的地址。

  2. NSString與NSNumber不一樣。

正確和簡化代碼應該是這樣的:

int randomNumber = (arc4random() % 5) + 1; 
// no need to create an NSNumber if you do not need to store it into an NS container. 

randLabel.text = [NSString stringWithFormat:@"It worked! %d", randomNumber]; 
// no need to create an intermediate NSString variable. 
// you can directly assign the string to the label's text. 
+0

真棒,即固定它。也很好解釋,所以我可以看到出了什麼問題。謝謝一堆(: – espekia 2010-10-05 15:46:31