我在我的模型中将对象添加到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);
}
导致此错误的原因是什么?
答案 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
。