0

I have 2 buttons: button1 and button2. I want to create a NSSet each for a correspond button touched and want to display set1 value when button 2 is touched and vice-versa. Only set 1 prints when button1 is pressed and only set2 when button 2 is pressed. How can i retain the set created in button1 action so that it can be displayed/used when button 2 is pressed. Have a look at my simple code

In implementation i have:

- (IBAction)button1:(UIButton *)sender {

    //somecode

    selectionButton1 = [[NSMutableArray alloc ] initWithObjects:@0,@1,@1,@4,@6,@11, nil];

    NSMutableSet *set1 = [NSMutableSet setWithArray: selectionButton1];
    NSLog(@"selectionButton1  = %@", set1);
    NSLog(@"selectionButton2  = %@", set2);
}


- (IBAction)button2:(UIButton *) sender {

    //somecode

    selectionButton2 = [[NSMutableArray alloc ] initWithObjects:@0,@5,@6,@7,@8,@10, nil];
    NSMutableSet *set2 = [NSMutableSet setWithArray: selectionButton2];
    NSLog(@"selectionButton1  = %@", set1);
    NSLog(@"selectionButton2  = %@", set2);
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
amystic
  • 5
  • 3

1 Answers1

1

Make properties for your sets. If you don’t need to access them from other classes, make them internal properties in a private class extension in your .m file. Then use self.propertyName to access the properties:

MyClass.m:

@interface MyClass // Declares a private class extension

@property (strong, nonatomic) NSMutableSet *set1;
@property (strong, nonatomic) NSMutableSet *set2

@end

@implementation MyClass

- (IBAction)button1:(UIButton *)sender {

    //somecode

    selectionButton1 = [[NSMutableArray alloc ] initWithObjects:@0,@1,@1,@4,@6,@11, nil];

    self.set1 = [NSMutableSet setWithArray: selectionButton1];
    NSLog(@"selectionButton1  = %@", self.set1);
    NSLog(@"selectionButton2  = %@", self.set2);
}


- (IBAction)button2:(UIButton *) sender {

    //somecode

    selectionButton2 = [[NSMutableArray alloc ] initWithObjects:@0,@5,@6,@7,@8,@10, nil];
    self.set2 = [NSMutableSet setWithArray: selectionButton2];
    NSLog(@"selectionButton1  = %@", self.set1);
    NSLog(@"selectionButton2  = %@", self.set2);
}

@end

For more on properties, see Apple’s documentation.

Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82
  • Even easier: `self.set1 = [NSMutableSet setWithArray: @[@0,@1,@1,@4,@6,@11]];` – zaph Sep 13 '14 at 04:30
  • 1
    Agreed. I was trying to keep as much of OP’s code intact as possible, but this is a cleaner way to do it. – Zev Eisenberg Sep 13 '14 at 04:33
  • Yeah, I debated wether to add the comment to your answer of the question. – zaph Sep 13 '14 at 04:35
  • Worked. Thanks every body @ZevEisenberg i needed array so i had to have it.Do you think if i keep the above code in some methods eg. -(void)selectedSet; will that work? – amystic Sep 13 '14 at 06:48
  • @amystic sorry, I don’t understand. What are you asking? You may want to try posting a new question. – Zev Eisenberg Sep 13 '14 at 06:51