好的,首先,您正在创建一个本地范围的数组,该数组在每次调用时都会重新初始化按钮点击:。该变量应该是类初始化周期的一部分。
您也会过得更好NSMutableDictionary而不是 NSMutableArray。使用字典,我们不必指定容量,我们可以使用按钮的标签作为字典键。
这就是您需要做的,这三个步骤始终一起进行:属性/合成/释放。一个值得记住的好人。
//Add property declaration to .h file
@property (nonatomic, retain) NSMutableDictionary * theseButtonsHaveBeenClicked;
//Add the synthesize directive to the top of .m file
@synthesize theseButtonsHaveBeenClicked;
// Add release call to the dealloc method at the bottom of .m file
- (void) dealloc {
self.theseButtonsHaveBeenClicked = nil; // syntactically equiv to [theseButtonsHaveBeenClicked release] but also nulls the pointer
[super dealloc];
}
接下来,我们在初始化类实例时创建一个存储对象。将其添加到您的班级中init or viewDidLoad method.
self.theseButtonsHaveBeenClicked = [[NSMutableDictionary alloc] dictionary]; // convenience method for creating a dictionary
还有你更新的按钮点击:方法应该看起来更像这样。
-(void) buttonClicked:(UIButton *)sender {
NSNumber *senderTagAsNum = [NSNumber numberWithInt:sender.tag];
NSString *senderTagAsString = [[NSString alloc] initWithFormat:@"%@",senderTagAsNum];
// this block adds to dict on first click, removes if already in dict
if(![self.theseButtonsHaveBeenClicked objectForKey:senderTagAsString]) {
[self.theseButtonsHaveBeenClicked setValue:senderTagAsNum forKey:senderTagAsString];
} else {
[self.theseButtonsHaveBeenClicked removeObjectForKey:senderTagAsString]; }
[senderTagAsString release];
NSLog(@"%@", self.theseButtonsHaveBeenClicked);
}