按下按钮时如何在NSMutableArray中添加值

时间:2017-03-12 19:46:53

标签: ios objective-c

对于我的iOS应用程序我想启动NSMutableArray并使用按钮更改运行期间数组保存的Object。到目前为止,我能够在ViewController.m中的viewDidLoad {}中启动一个数组,但现在我无法在我的buttonPressed方法中访问它。如何使数组可以访问保存文件?

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSMutableArray *toCalculate = [@[@0] mutableCopy];
}


- (IBAction)numbersButtonsPressed:(UIButton *)sender {
    NSLog(@"%ld\n", sender.tag);
    [toCalculate addObject:[NSNumber numberWithLong:sender.tag]];
}

2 个答案:

答案 0 :(得分:0)

谢谢保罗, 如果你在ViewController.h文件中将它实现为@property,它就像他说的那样工作。

   @interface ViewController: UIViewController

   @propety NSMutableArray *giveItAName

   @end

答案 1 :(得分:0)

将变量声明为全局(类变量)而不是局部变量(函数)。

What is global variable?

问题的解决方案是:

#import "ViewController.h"

@interface ViewController (){
    NSMutableArray *toCalculate;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    toCalculate = [@[@0] mutableCopy];
    // Do any additional setup after loading the view, typically from a nib.
}



- (IBAction)numbersButtonsPressed:(UIButton *)sender {
    NSLog(@"%@",toCalculate);
    [toCalculate addObject:[NSNumber numberWithLong:sender.tag]];
}


@end