2014-09-13 45 views
0

我有2個按鈕:button1和button2。我想爲每個觸摸的對應按鈕創建一個NSSet,並且當按下按鈕2時要顯示set1值,反之亦然。按下按鈕1時僅設置1打印,按下按鈕2時僅設置2。我如何保留在button1動作中創建的設置,以便在按下按鈕2時可以顯示/使用它。看看我的簡單的代碼保留我新創建的NSSet

在實現我有:

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

回答

1

讓屬性的集合。如果您不需要從其他類訪問它們,請將它們作爲.m文件中私有類擴展名的內部屬性。然後使用self.propertyName訪問屬性:

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 

更多關於性能,見Apple’s documentation

+0

更簡單:'self.set1 = [NSMutableSet setWithArray:@ [@ 0,@ 1,@ 1,@ 4,@ 6,@ 11]];' – zaph 2014-09-13 04:30:17

+1

同意。我試圖儘可能保持OP的代碼完整無缺,但這是一種更乾淨的方式。 – 2014-09-13 04:33:48

+0

是的,我辯論過將這個評論添加到你的問題答案中。 – zaph 2014-09-13 04:35:16

相關問題