最近刚学iOS不久 跟着斯坦福上学着做计算器app
当用数组把操作数存入到栈中 发现数组中永远只有一个元素
@interface ViewController () @property (strong, nonatomic) IBOutlet UILabel *display; @end bool userIsInTheMiddleOfTyping = FALSE; @implementation ViewController - (IBAction)appendDigit:(UIButton *)sender { if(userIsInTheMiddleOfTyping){ NSString *digit = sender.currentTitle; _display.text = [_display.text stringByAppendingString:digit]; }else{ _display.text = sender.currentTitle; userIsInTheMiddleOfTyping=TRUE; } } - (IBAction)enter { userIsInTheMiddleOfTyping = FALSE; NSMutableArray *operandstack = [[NSMutableArray alloc]init]; [operandstack addObject:_display.text]; NSLog(@"operandstack = %li", operandstack.count); NSLog(@"operandstack = %@", operandstack); }
当点击一个enter按钮的时候 数组里就会加一个元素 但是情况是数组里永远只有一个元素
第一次点击后NSLog输出数组的count和内容的时候
2017-01-15 08:47:50.620 MYCalculator[32235:2359081] operandstack = 1 2017-01-15 08:47:50.622 MYCalculator[32235:2359081] operandstack = ( 3 )
之后第二次 第三次 都是显示有一个元素 永远是Label上那个最新的元素
2017-01-15 08:47:50.620 MYCalculator[32235:2359081] operandstack = 1 2017-01-15 08:47:50.622 MYCalculator[32235:2359081] operandstack = ( 3 ) 2017-01-15 08:52:20.332 MYCalculator[32235:2359081] operandstack = 1 2017-01-15 08:52:20.334 MYCalculator[32235:2359081] operandstack = ( 236 )
我就想知道之前加入数组的3 怎么不见了
小白一个 大神们轻喷
In Objective-C, alloc is to open up a memory space, and init is to initialize.
Every time you click the button, the array operandstack is re-initialized in the method
- (IBAction)enter
, and then new elements are added.- (IBAction)enter
中重新初始化了数组 operandstack ,然后加入新的元素。把 operandstack 数组写成 property ,然后在
- (void)viewDidLoad
Write the operandstack array as property, and then initialize it once in the- (void)viewDidLoad
method:Because the initialization code of NSMutablearray is placed in the click event, NSMutablearray is re-initialized every time it is clicked, which means that the previous elements are lost, so naturally, there is only one element. You can use NSMutablearray as a member variable or attribute to solve this problem.