我不明白为什么在我的 .m 文件中调用 mineHit 方法时会出现 EXC BAD ACCESS 错误。我知道这表明按钮数组已被释放,但我不明白为什么它会被释放。
#import "basicsViewController.h"
@implementation basicsViewController
@synthesize resetGame;
@synthesize scoreLabel;
@synthesize timeLabel;
@synthesize time;
@synthesize score;
-(void)newGame{
int index=0;
int yAxis=70;
for(int y=0;y<100;y=y+10){
int xAxis=20;
for( int x = 1; x < 11; x++) {
buttonArray[index] = [[UIButton alloc]init];
buttonArray[index] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonArray[index] setTag:index];
[buttonArray[index] addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
buttonArray[index].frame = CGRectMake(xAxis, yAxis, 26.0, 26.0);
NSLog(@"tag:%d xAxis:%d yAxis:%d",buttonArray[index].tag,(int)buttonArray[index].frame.origin.x,(int)buttonArray[index].frame.origin.y);
[self.view addSubview:buttonArray[index]];
xAxis=xAxis+28;
index=x+y;
}
yAxis=yAxis+28;
}
//generate bombs
for (int bombs=0;bombs<10;bombs++){
bombArray[bombs]= (arc4random()%99);
//TODO compare against bombArray to make sure of no duplicates
NSLog(@"BOMB AT %d",bombArray[bombs]);
}
}
- (IBAction)resetPress:(id)sender {
[self newGame];
}
- (void)buttonClicked:(UIButton*)button
{
BOOL hit;
NSLog(@"SELECTED BUTTON:%d",button.tag);
for (int b=0;b<10;b++){
if (button.tag==bombArray[b]){
//BOMB HIT
hit=YES;
b=10;
}
else {
//no bomb
hit=NO;
}
}
if (hit==YES){
//if hit
NSLog(@"HIT AT %d",button.tag);
[self mineHit];
}
else {
//if not hit
NSLog(@"%d is clean",button.tag);
[self cleanHit:button];
}
}
-(void)mineHit{
for (int d=0;d<100;d++){
NSLog(@"%i",buttonArray[d].tag);
buttonArray[d].enabled=NO;
[buttonArray[d] setTitle:@"*" forState:UIControlStateDisabled];
}
}
-(void)cleanHit:(UIButton*)button{
button.enabled=NO;
[button setTitle:@"!" forState:UIControlStateDisabled];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self newGame];
}
- (void)viewDidUnload
{
[self setResetGame:nil];
[self setScoreLabel:nil];
[self setTimeLabel:nil];
[super viewDidUnload];
}
@end
这是我的 .h 文件
#import <UIKit/UIKit.h>
NSInteger bombArray[];
UIButton *buttonArray[];
@interface basicsViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *resetGame;
@property (weak, nonatomic) IBOutlet UILabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property int time;
@property int score;
-(void)newGame;
-(void)buttonClicked:(UIButton*)button;
-(void)mineHit;
-(void)cleanHit:(UIButton*)button;
@end