我有2个按钮:button1和button2。我想为每个对应的按钮创建一个NSSet,并想在触摸按钮2时显示set1值,反之亦然。按下按钮1时仅打印设置1,按下按钮2时仅打印设置2。我如何保留在button1动作中创建的集合,以便在按下按钮2时可以显示/使用它。看看我的简单代码

在实现中,我有:

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

最佳答案

为您的集合设置属性。如果您不需要从其他类访问它们,请在.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

关于ios - 保留我新创建的NSSet,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25819625/

10-10 21:03