ios - OC中一个关于数组的问题。
天蓬老师
天蓬老师 2017-04-18 09:51:32
0
2
332

最近刚学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 怎么不见了

小白一个 大神们轻喷

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all (2)
Ty80

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)viewDidLoadWrite the operandstack array as property, and then initialize it once in the- (void)viewDidLoadmethod:

- (void)viewDidLoad { self.operandstack = [NSMutableArray array]; }
    伊谢尔伦

    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.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!