NSMutablearray - “不是Objective-C对象”错误

时间:2012-08-03 01:13:27

标签: objective-c ios nsmutablearray

我不完全确定为什么它会在注释行返回错误“not a objective-C object”。任何帮助将不胜感激。

另外,我对Objective-C很新,我确实意识到这是一个非常愚蠢的错误。但是,任何建议都会有所帮助。

#import "CalculatorBrain.h"

@interface CalculatorBrain()
@property (nonatomic, strong) NSMutableArray *operandStack;
@end

@implementation CalculatorBrain

@synthesize operandStack = _operandStack;

- (NSMutableArray *)operandStack
{
    if(!_operandStack){
    _operandStack = [[NSMutableArray alloc] init];
    }// end if
    return _operandStack;
}//end operandStack

- (void)pushOperand:(double)operand
{
    NSNumber *operandObject = [NSNumber numberWithDouble:operand];
    [self.operandStack addObject:operandObject];
}//end pushOperand

- (double)popOperand
{
    NSNumber *operandObject = [self.operandStack lastObject];//error "Not an objective-c object"
    if(operandObject) [self.operandStack removeLastObject];
    return [operandObject doubleValue];
}//end popOperand

- (double)performOperation:(NSString *)operation
{
    double result = 0;

    if([operation isEqualToString:@"+"]){
    result = [self popOperand] + [self popOperand];
} else if([operation isEqualToString:@"-"]){
    double subtrahend = [self popOperand];
    result = [self popOperand] - subtrahend;
} else if([operation isEqualToString:@"*"]){
    result = [self popOperand] * [self popOperand];
} else if([operation isEqualToString:@"/"]){
    double divisor = [self popOperand];
    if(divisor) result = [self popOperand] / divisor;
}//end if
[self pushOperand:result];
return result;

}//performOperation

@end

1 个答案:

答案 0 :(得分:0)

我认为这可能是由函数popOperand中的错误操作顺序引起的。看看我的内联注释,最后一行返回[operandObject doubleValue]访问已经发布的对象。多次运行此代码后,可能会导致内存问题,反过来,您可能会在注释行中看到错误。

- (double)popOperand
{
    NSNumber *operandObject = [self.operandStack lastObject];
    if(operandObject) [self.operandStack removeLastObject];
    // When you remove the lastObject(operandObject) from the Array, the operandObject retainCount is zero.
    // Here, the operandObject is deallocated and should not be used.
    // But you call it after it was released.
    return [operandObject doubleValue];
}//end popOperand

当您只调用一次或多次popOperand时,这可能没问题。但这会导致内存错误。我猜每次调用popOperand时都不会发生错误。这是我的解决方案。

- (double)popOperand
{
    double result = 0.0;
    NSNumber *operandObject = [self.operandStack lastObject];
    if(operandObject) 
    {
        result = [operandObject doubleValue];
        [self.operandStack removeLastObject];
    }
    return result;
}