对NSMutableArray方法的简单addObject给出了lldb错误

时间:2012-11-20 00:32:33

标签: objective-c ios nsmutablearray

我在我的模型中将对象添加到NSMutableArray堆栈。这是界面:

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

@end

实施:

@implementation calcModel
@synthesize operandStack = _operandStack;

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

这个addobject方法工作正常:

- (void)pushValue:(double)number;
{
[self.operandStack addObject:[NSNumber numberWithDouble:number]];
NSLog(@"Array: %@", self.operandStack);
}

但是这个应用程序崩溃了,只是在日志中说“lldb”:

- (void)pushOperator:(NSString *)operator;
{
[self.operandStack addObject:operator];
NSLog(@"Array: %@", self.operandStack);
}

导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:3)

您要添加的NSString可能是nil。这样做:

- (void)pushOperator:(NSString *)operator {
    if (operator) {
        [self.operandStack addObject:operator];
        NSLog(@"Array: %@", self.operandStack);
    } else {
        NSLog(@"Oh no, it's nil.");
    }
}

如果是这种情况,请找出原因nil并解决问题。或者在添加之前检查它。

第一种方法没有崩溃的原因是,因为没有不能用于初始化NSNumber的double值,所以它永远不会是nil