访问NSMutableArray的困难

时间:2011-12-30 06:29:17

标签: objective-c ios cocoa-touch

每次按下按钮时,我都会尝试构建一个NSMutableArray。在按下每个按钮后,我使用NSLog检查数组计数,值为零。代码如下。

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];

虽然我在头文件中声明了数组,但似乎我无法在分配它的方法之外访问它。

2 个答案:

答案 0 :(得分:1)

看起来您从未分配过numberQuery。所以它总是为零,因此addObject方法被忽略。您需要在init(或您喜欢的任何合适位置)中分配此内容,然后在dealloc(或其他合适的位置)发布。

答案 1 :(得分:1)

@property (nonatomic, retain) NSMutableArray *numberQuery;

您必须与

保持平衡
@synthesize numberQuery;
<。> <。>

正确的创作将是

self.numberQuery = [NSMuatableArray arrayWithCapacity:someNumber];

通过这样做

NSMutableArray *numberQuery = [[NSMutableArray alloc] initWithObjects:nil];

你没有使用你正在创建新变量的@property,这就是你得到你的变量没有用的警告的原因,因为它的范围实际上只是viewDidLoad方法而不是对象。 / p>