首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NSString分配中的无效摘要

NSString分配中的无效摘要
EN

Stack Overflow用户
提问于 2011-05-11 02:15:09
回答 2查看 2.2K关注 0票数 0

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

代码语言:javascript
复制
 -(double)doOperation:(NSString *)operation withOperand:(double)operand
 {
     if (!currentOperation)
     {
         anOperand = operand;
     }   

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

这里面有什么不对的?如果NSString不允许直接分配指针,那么替代方法是什么?

编辑

  1. 更准确地说,在iOs中指定NSString和= sign是否合法?
  2. 如果没有,还有什么路要走。

注意: currentOperation是Controller类中的私有变量,而操作是该方法的参数。

这是完整的代码

代码语言:javascript
复制
@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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-05-11 14:06:12

更准确地说,在iOs中指定NSString和= sign是否合法?

是。

这里面有什么不对的?

如果以后要使用实例,则不会获得字符串的所有权,这将导致问题,请参阅内存管理指南

您可以使用retain获取对象的所有权。 记住,一个对象可能有多个所有者。拥有一个物体是你说你需要让它活着的方式。

您可以对字符串进行-retain,或者-copy,以避免外部代码发生变异,例如:

代码语言:javascript
复制
// in -doOperation::
[currentOperation release];
currentOperation = [operation copy]; // copy if operation might be mutable

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

还可以查看声明属性

票数 4
EN

Stack Overflow用户

发布于 2011-05-11 13:57:38

如果currentOperation被声明为NSString,请尝试

代码语言:javascript
复制
currentOperation = [NSString stringWithString:operand];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5958504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档