我試圖每次按下按鈕時生成一個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