Search code examples
iosnssetnsmutableset

Retaining my newly created NSSet


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);
}

Solution

  • 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.