2012-11-13 64 views
0

我嘗試這樣的:添加兩個NSString的共同(數字)

NSNumber *num1; 
    NSNumber *num2; 
    self.addNumberOfRoundsText.text = [num1 stringValue]; 
    self.numberOfRoundsText.text = [num2 stringValue]; 
    NSNumber *sum = [NSNumber numberWithInt:([num1 intValue] + [num2 intValue])]; 
    NSLog(@"%@", [sum stringValue]); 

出於某種原因,控制檯保持輸出0林不知道,如果有什麼我失蹤。我只想從兩個UITextField獲得text並添加它們。然後將它們輸出到控制檯。感謝您的幫助!

+1

...你什麼時候讀入'num1'和'num2'?看起來你正在分配文本字段的值,而不是檢索它們。 – Xymostech

回答

4

在你的示例代碼,你沒有初始化num1num2。所以(如果你使用的ARC,這是新項目的默認值),那些變量初始化爲零。

在Objective-C中,您可以發送任何消息(如stringValueintValue)爲零,並返回0或零。所以:

NSNumber *num1; // initialized to nil by ARC 
NSNumber *num2; // initialized to nil by ARC 

// This sets self.addNumberOfRoundsText.text to nil. 
self.addNumberOfRoundsText.text = [num1 stringValue]; 

// This sets self.numberOfRoundsText.text to nil. 
self.numberOfRoundsText.text = [num2 stringValue]; 

// This gets 0 for [num1 intValue] and 0 for [num2 intValue], which add up 
// to 0, so sum is an NSNumber representing zero. 
NSNumber *sum = [NSNumber numberWithInt:([num1 intValue] + [num2 intValue])]; 
NSLog(@"%@", [sum stringValue]); 

我不確定你究竟在做什麼。也許你有兩個文本字段,每個文本字段都包含一個數字,並且你想要將這兩個數字相加。如果這是你想要做什麼,試試這個:

int n1 = self.addNumberOfRoundsText.text.intValue; 
int n2 = self.numberOfRoundsText.text.intValue; 
int sum = n1 + n2; 
NSLog(@"sum = %d", sum); 
+0

+1因爲我不知道ARC自動做到了! – borrrden

+0

+1因爲你回答了我的問題,你是一個不好的屁股!多謝兄弟 –

0

這裏是代碼,你問你要添加兩個UITextField值成一個單一String

NSString* finalSTring; 

    finalSTring =[NSString stringWithFormat:@"%@%@",textfield1.text,textField2.text]; 
    //textField1 and Textfield2 is instance of TextField. 

    NSLog(@"%@",finalSTring);//here you have new Single String 
0

如果你有兩個文本字段:field1field2

int sum = [field1.text intValue] + [field2.text intValue]; 

或者,如果你想總結爲NSNumber

NSNumber* sum = [NSNumber numberWithInt:[field1.text intValue] + [field2.text intValue]]; 
0

爲什麼不這樣設置呢

NSNumber *num1; 
NSNumber *num2; 
self.addNumberOfRoundsText.text = [NSString stringWithFormat:@"%@",num1]; 
self.numberOfRoundsText.text = [NSString stringWithFormat:@"%@",num2]; 

NSNumber *sum = num1 + num2 ; 
NSLog(@"%@", sum);