-4

for my iOS app I want to initiate an NSMutableArray and change the Object the array holds during runtime with buttons. So far I was able to initiate an array in viewDidLoad {} in the ViewController.m but now i can't access it in my buttonPressed method. How can I make the array accessible for the hold file?

#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]];
}
Sakir Sherasiya
  • 1,562
  • 1
  • 17
  • 31
Amir A.
  • 35
  • 3
  • 1
    Please put your code in the question, not as a screenshot. You need to declare your array as a property, not a local variable in `viewDidLoad` – Paulw11 Mar 12 '17 at 20:00

2 Answers2

0

Thanks Paul, it work like he said if you implement it as a @property in the ViewController.h file.

   @interface ViewController: UIViewController

   @propety NSMutableArray *giveItAName

   @end
Amir A.
  • 35
  • 3
0

Declare variable as global(class variable) not in local variable(function).

What is global variable?

Solution for the problem is:

#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
Community
  • 1
  • 1
Sakir Sherasiya
  • 1,562
  • 1
  • 17
  • 31