1

I am new to objective C and trying to learn it. I am trying to write calculator program which performs simple mathematical calculation(addition, subtraction and so forth).

I want to create an array which stores for numbers(double value) and operands. Now, my pushOperand method takes ID as below:

-(void) pushOperand:(id)operand
{
    [self.inputStack addObject:operand];

}

when I try to push double value as below:

- (IBAction)enterPressed:(UIButton *)sender
{

    [self.brain pushOperand:[self.displayResult.text doubleValue]];
}

It gives my following error: "Sending 'double' to parameter of incompatible type 'id'"

I would appreciate if you guys can answer my following questions:

  1. 'id' is a generic type so I would assume it will work with any type without giving error above. Can you please help me understand the real reason behind the error?

  2. How can I resolve this error?

2 Answers 2

1

id is a pointer to any class. Hence, it does not work with primitive types such as double or int which are neither pointers, nor objects. To store a primitive type in an NSArray, one must first wrap the primitive in an NSNumber object. This can be done in using alloc/init or with the new style object creation, as shown in the two snippets below.

old style

NSNumber *number = [[NSNumber alloc] initWithDouble:[self.displayResult.text doubleValue]];
[self.brain pushOperand:number];

new style

NSNumber *number = @( [self.displayResult.text doubleValue] );
[self.brain pushOperand:number];
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest using it with an NSNumber: Try not to abuse using id where you don't need to; lots of issues can arise if not.

- (void)pushOperand:(NSNumber *)operand
{
    [self.inputStack addObject:operand];
}

- (IBAction)enterPressed:(UIButton *)sender
{
    [self.brain pushOperand:@([self.displayResult.text doubleValue])];
}

1 Comment

You should also be able to use the short-hand @([self.displayResult.text doubleValue]) rather than [NSNumber numberWithDouble:[self.displayResult.text doubleValue]] to make it a bit more concise, but yes you can't push primitives into an objective-C array or pass as a generic objective-c object (id) because it's not an object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.