我试图每次按下按钮时生成一个NSMutableArray。我使用NSLog来检查按下每个按钮后的数组数量,值为零。代码如下。访问NSMutableArray困难
ProjectViewController.h
NSMutableArray *numberQuery
...
@property (nonatomic, retain) NSMutableArray *numberQuery;
ProjectViewController.m
- (void)makeButtons{
UIButton * pickButton;
int y_plot = 150;
int x_plot = 70;
int z = 0;
for(int y = 1; y < 10; y++)
{
for(int x = 1; x < 5; x++){
z++;
pickButton = [UIButton buttonWithType:UIButtonTypeCustom];
pickButton.frame = CGRectMake(x*x_plot, y_plot, 60, 40);
[pickButton setBackgroundImage:[UIImage imageNamed:@"btnUnselected.png"] forState:UIControlStateNormal];
[pickButton addTarget:self action:@selector(digitClick:) forControlEvents:UIControlEventTouchUpInside];
[pickButton setTitle:[NSString stringWithFormat:@"%d",z] forState:UIControlStateNormal];
pickButton.titleLabel.textColor = [UIColor blackColor];
pickButton.tag = z;
[self.view addSubview:aButton];
}
y_plot=y_plot+45;
}
}
//************************
- (void)digitClick:(id)sender{
UIButton * chosenButton =(UIButton *)sender;
if ([sender isSelected] ==FALSE) {
[sender setSelected:TRUE];
[chosenButton setBackgroundImage:[UIImage imageNamed:@"btnSelected.png"] forState:UIControlStateNormal];
chosenButton.titleLabel.textColor = [UIColor whiteColor];
if([queryNumbersX count]<6){
[self numberSearchArray:chosenButton.tag];
}
}
else
{[sender setSelected:FALSE];
[chosenButton setBackgroundImage:[UIImage imageNamed:@"btnUnselected.png"]forState:UIControlStateNormal];
chosenButton.titleLabel.textColor = [UIColor blackColor];
}
forState:UIControlStateNormal];
NSLog(@"clicked button with title %d",chosenButton.tag);
}
//************************
-(void) numberSearchArray:(NSInteger)newNumber;
{
[self.numberQuery addObject:[NSNumber numberWithInt: newNumber]];
NSLog(@"numberSearchArray %d - count %d",newNumber, [self.numberQuery count]);
}
我使用的NSMutableArray的正确的方式...声明?
这是viewDidLoad方法
NSMutableArray *numberQuery = [[NSMutableArray alloc] initWithObjects:nil];
代码虽然我有阵宣布诠释他的头文件,它好像我不能在其被分配的方法之外访问它。
你也可以使用一个方便的方法'self.numberQuery = [NSMutableArray array];'。这个数组是autoreleased,所以你的保留属性是平衡的。同样使用'initWithObjects:'并传递nil看起来很可疑。 – vikingosegundo 2011-12-30 16:14:13
@vikingosegundo你是对的我会修改它为'+(id)arrayWithCapacity:(NSUInteger)numItems'那会更好 – 2011-12-30 16:18:47
THanks,VinceBurn!现在工作完美! – 2011-12-30 16:20:19