objective-c - NSString 分配中的摘要无效

标签 objective-c ios

我正在尝试实现一个简单的计算器,我必须在 NSString 类型的变量中更新当前操作(+、-、* 等)。当前操作作为参数接收到模型。

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

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

这有什么问题?如果 NSString 不允许直接赋值指针,替代方法是什么?

编辑

  1. 更准确地说,在 iOs 中使用 = 号分配 NSString 是否合法?
  2. 如果没有,该怎么走?

注意:currentOperation是Controller类中的私有(private)变量,operation是方法的参数。

完整代码如下

@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: @"+"])
    {
        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?

是的。

What could be wrong in this?

您没有取得字符串的所有权,如果您想稍后使用该实例,这将导致问题,请参阅 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.

您可以-retain 字符串,或-copy 以避免外部代码的突变,例如:

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

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

另请查看 declared properties .

关于objective-c - NSString 分配中的摘要无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5958504/

相关文章:

objective-c - 如何为 UITableViewController 中不同部分的每一行指定高度?

objective-c - 对象的 NSArray 的 RACSignal

ios - 如何在iOS中制作水平滚动菜单

iphone - 如何在选择器 View iOS 中设置文本对齐方式

ios - NSURLSession backgroundSession 完成时额外的 API 调用

ios - 方法返回的对象会被放入自动释放池吗?

iphone - 限制 NSTableView 列中单元格中的文本长度

iphone - 从相机胶卷中选择的视频的 URL

ios - 命令因信号 : Segmentation fault: 11 而失败

iphone - iOS:当 iphone 处于 sleep 模式或当我按下主页按钮时执行 NSURLConnection