-6

I am quite new to iOS programming. Can anyone help me on how to create two buttons (button 1 and button 2) that add integers (integer 1 and integer 2) to a Mutable array when each button is clicked? Means that when Button 1 is clicked, integer 1 is added to the mutable array, and when integer 2 is clicked, integer 2 will be added to the mutable array. I understand we need to create an instance of the mutable array before we can use the array, but I'm not sure where is the best place to do that?

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableArray *inputArray = [[NSMutableArray alloc] init];
}

- (IBAction)Button1:(id)sender {
int _userinput = 1;
NSNumber *userinput = [NSNumber numberWithInteger:_userinput];
[self.inputArray addObject:userinput];
NSLog(@"%@", self.inputArray[0]);
}
Dick Lee
  • 1
  • 2
  • 1
    The way to learn is by doing. Try something, post the code and ask for help. – zaph Jan 07 '15 at 01:37
  • Did you already try to do this? – MaappeaL Jan 07 '15 at 03:19
  • If you're just starting out, asking people for code like this on Stack Overflow is not the place you need to be. You should find a good book or a series of online tutorials. Have a look at [Good resources for learning ObjC](http://stackoverflow.com/q/1374660). The Big Nerd Ranch books are excellent, and lots of people like the Stanford iOS course on iTunes U. Good luck! – jscs Jan 07 '15 at 05:14

1 Answers1

0

You can create instance variable of NSMutableArray and two buttons with setting tag value and on clicking the same you can add it to array.like that below:-

- (void)viewDidLoad 
{
    [super viewDidLoad];
    self.mutArr=[NSMutableArray array];
    NSUInteger j=0;
    for(NSUInteger i=0; i<2; i++)
    {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(buttonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:[NSString  stringWithFormat:@"%@ %ld",@"Button",i+1] forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0+j, 210.0, 160.0, 40.0);
    [self.view addSubview:button];
    button.tag=i+1;
    j=100;
    }
}

-(void)buttonClicked:(id)sender
{
    [self.mutArr addObject:@([sender tag])];
    NSLog(@"%@",self.mutArr);
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56