簡體   English   中英

訪問NSMutableArray的困難

[英]Accessing NSMutableArray Difficulties

我每次按下按鈕時都會嘗試構建一個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];

雖然我在頭文件中聲明了數組,但似乎我無法在分配它的方法之外訪問它。

看起來你從未分配過numberQuery 因此它總是為零,因此忽略addObject方法。 你需要在init (或你喜歡的任何合適的地方)中分配它,並在dealloc (或其他合適的地方)發布。

@property (nonatomic, retain) NSMutableArray *numberQuery;

你必須與之保持平衡

@synthesize numberQuery;

在他們中

並且正確的創造將是

self.numberQuery = [NSMuatableArray arrayWithCapacity:someNumber];

通過做這個

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

你沒有使用你正在創建新變量的@property,這就是為什么你得到你的變量沒有使用的警告,因為它的范圍實際上只是viewDidLoad方法而不是對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM