将 NSString 和 NSNumber 放入数组的方法
这是一个计算器。我有一个显示器,可以在其中输入数字和变量(x、y 等)。当我按下 Enter 按钮时,它将显示的内容与所有操作数一起发送到数组。
由于显示可以是 NSString (变量)或 NSNumber (数字),我想使用“id”作为方法参数。
- (IBAction)enterPressed
{
[self.brain pushOperand:self.display.text];
}
/////////////////////
- (void) pushOperand:(id)operand
{
////// So if operand is digit I need to transform it into NSNumber.
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
/////// Here is problem - "Sending '___strong id' to parameter of incompatible type 'double'
NSNumber *digitToStack = [operand doubleValue];
//////// If i do like this, i have warning - "Initializing 'NSNumber *__strong' with an expression of incompatible type 'double'
[self.programStack addObject:operand];
}
我不明白这个警告是什么意思。
所以问题是我可以使用 id 方法放入 Array NSNumber 和 NSString 吗?或者我应该怎么做?
我可以将参数从“id”方法“转换”为 NSNumber 吗?
It's a calculator. I have a display where I can put digits and variables (x, y etc.). When I push Enter button it sends what is on display to array with all operand.
As on display can be NSString (variables) or NSNumber (digits) I thought to use "id" as method argument.
- (IBAction)enterPressed
{
[self.brain pushOperand:self.display.text];
}
/////////////////////
- (void) pushOperand:(id)operand
{
////// So if operand is digit I need to transform it into NSNumber.
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
/////// Here is problem - "Sending '___strong id' to parameter of incompatible type 'double'
NSNumber *digitToStack = [operand doubleValue];
//////// If i do like this, i have warning - "Initializing 'NSNumber *__strong' with an expression of incompatible type 'double'
[self.programStack addObject:operand];
}
I don't understand what this warnings are all about.
So the question is can I somehow put in Array NSNumber and NSString using id method, or how should I do it?
Can i 'transform' argument from 'id' method into NSNumber?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,您可以“转换”您的操作数参数,但您需要进行强制转换。
此外,行:
失败,因为“操作数”是 Objective C 对象,而该函数需要 C 风格的 double 类型(它不是 Objective C 对象)。
这是我随手写下的一些代码:
该代码尚未经过测试,没有保证,并且肯定可以使用进一步的清理和优化(例如,对“0.0”的检查不是我要放入的内容)生产代码,我自己)。
但希望这足以让你走得更远,萨沙!
Yes you can "transform" your argument of
operand
, but you'd need to do a cast.Also, the line:
fails because "operand" is an Objective C object while that function is expecting a C-style
double
type (which is NOT an Objective C object).Here's some code I wrote off the top of my head:
This code hasn't been tested, has no warranties, and could certainly use a further cleaning up and optimization (e.g. the check for "0.0" isn't what I would put into production code, myself).
But hopefully this is enough to get you further along, Sasha!