开发者

Invalid Summary in NSString assignment

I am trying to implement a simple calculator where I have to update the current operation (+, -, * etc) in a variable of type NSString. Current operation is received to the Model as a parameter.

 -(double)doOperation:(NSString *)operation withOperand:(double)operand
 {
     if (!currentOperation)
     {
         anOperand = operand;
     }   

     currentOperation = operation; //Invalid Summary in currentOperation; but + in operation
 }

What could be wrong in this? If direct assignment of pointers are not allowed for NSString, what is the alternate method?

EDIT

  1. To be more precise, is it legal in iOs to assign NSString with = sign?
  2. If not, what is the way to go.

Note: currentOperation is a private variable in Controller class and operation is a parameter to the method.

Here is the complete code

@interface CalculatorBrain : NSObject {
    double anOperand;
    NSString * currentOperaion;
}

- (double) doOperation: (NSString *) operation 
           withOperand: (double) operand;

@end



@implementation CalculatorBrain


- (double) doOperation: (NSString *) operation 
           withOperand: (double) operand
{
    if (!currentOperaion)
    {
        anOperand = operand;
    }
    else if([currentOperaion isEqual: @"+"])
    {
    开发者_C百科    anOperand += operand;
    }
    else if([currentOperaion isEqual: @"-"])
    {
        anOperand -= operand;
    }
    else if([currentOperaion isEqual: @"*"])
    {
        anOperand *= operand;
    }
    else if([currentOperaion isEqual: @"/"])
    {
        anOperand /= operand;
    }

    currentOperaion = operation; //This is where the statement doesn't work as expected

    if ([currentOperaion isEqual: @"="])
    {
        currentOperaion = nil;
    }

    return anOperand;
}

@end


To be more precise, is it legal in iOs to assign NSString with = sign?

Yes.

What could be wrong in this?

You are not taking ownership of the string which will lead to problems if you want to use the instance later, see the memory management guide:

You can take ownership of an object using retain.
Remember that an object may have more than one owner. Taking ownership of an object is your way of saying that you need it to be kept alive.

You could -retain the string, or -copy it to avoid mutation from external code, e.g.:

// in -doOperation::
[currentOperation release];
currentOperation = [operation copy]; // copy if operation might be mutable

// relinquish ownership:
- (void)dealloc {
    [currentOperation release];
    [super dealloc];
}

Also look into declared properties.


If currentOperation is declared as NSString, try

currentOperation = [NSString stringWithString:operand];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜