我正在尝试实现一个简单的计算器,我必须在 NSString 类型的变量中更新当前操作(+、-、* 等)。当前操作作为参数接收到模型。
-(double)doOperation:(NSString *)operation withOperand:(double)operand
{
if (!currentOperation)
{
anOperand = operand;
}
currentOperation = operation; //Invalid Summary in currentOperation; but + in operation
}
这有什么问题?如果 NSString 不允许直接赋值指针,替代方法是什么?
编辑
- 更准确地说,在 iOs 中使用 = 号分配 NSString 是否合法?
- 如果没有,该怎么走?
注意: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/