在你的示例代码,你没有初始化num1
和num2
。所以(如果你使用的ARC,这是新项目的默认值),那些变量初始化为零。
在Objective-C中,您可以发送任何消息(如stringValue
或intValue
)为零,并返回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);
...你什么时候读入'num1'和'num2'?看起来你正在分配文本字段的值,而不是检索它们。 – Xymostech