这是代码
在.h ...
@interface Calculator2ViewController : UIViewController {
NSString *currentNumber;
bool buildingNumber;
NSMutableArray *arrayExpression;
IBOutlet UILabel *display;
}
在.m ...
-(NSString *) makeCurrentNumber{
if(!currentNumber){
currentNumber = [[NSString alloc] init];
currentNumber = @"";
}
NSLog(@"Inside make makeCurrentNumber. The currentNumber is %@",currentNumber);
return currentNumber;
}
-(IBAction) digitPressed: (UIButton *)sender{
NSString *digit = sender.titleLabel.text;
NSLog(@"The digit is: %@", digit);
if(!currentNumber)
currentNumber = @"";
currentNumber = [currentNumber stringByAppendingString:digit];
NSLog (@"The string is: %@",currentNumber);
buildingNumber = YES;
}//end of digitPressed
为什么我的程序会在3次追加后崩溃?
答案 0 :(得分:2)
currentNumber最初由makeCurrentNumber中的alloc-init保留。稍后,您将使用自动保留值替换其值(stringByAppendingString
的结果。使用保留增强该行,您可能会获得更好的结果。
[...]
if(!currentNumber)
{
[self makeCurrentNumber];
}
currentNumber = [[currentNumber stringByAppendingString:digit] retain];
NSLog (@"The string is: %@",currentNumber);
[...]