2010-11-23 9 views
0

私はビューに表示するイメージの配列を作成するためのこのコードを持っています。私のビューのページのほとんどは、20の画像(5の列、4の行)を持ちますが、実際には43の画像があり、画像配列に最終3が含まれていると、内側の4番目の繰り返しループでは、配列は空です。Out of Bounds空白のNSArrayの例外

- (void)displayImages:(NSMutableArray *)images { 

NSMutableArray *keysArray = [[NSMutableArray alloc] initWithCapacity:5]; 

for (int column = 0; column < 5; column++){ 
    [keysArray addObject:[NSMutableArray arrayWithCapacity:5]]; 
    for (int row = 0; row < 4; row++) { 
     [[keysArray objectAtIndex:column] addObject:[images objectAtIndex:0]]; 
     [images removeObjectAtIndex:0]; 
    } 
} 

.... 

この問題を回避できますか?

ありがとうございました。

EDIT:

このコードに続き、実際のアレイから画像を引っ張るコードです。しかし、同じシナリオが発生します.4回目の繰り返しでクラッシュします。

for (int column = 0; column < 5; column++) { 
    for (int row = 0; row < 4; row++){   
     UIButton *keyButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     keyButton.frame = CGRectMake(column*kKeyGap, row*kKeyGap, kKeySize, kKeySize); 

     [keyButton setImage:[[keysArray objectAtIndex:column] objectAtIndex:row] forState:UIControlStateNormal]; 
     [keyButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

     [self.view addSubview:keyButton]; 
    } 
} 
[keysArray release]; 

アレイが既に空にされるように私はこの時点でimagesをテストすることはできません。

答えて

0

は、実際の配列のサイズの代わりに定数を使用してみてくださいかを確認しforループテキスト式の値。だから、むしろこれより:

for (int column = 0; column < 5; column++) 

は、次の操作を行います。

for (int column = 0; column < [keysArray count]; column++) 

結果のコードは次のようになります:ところで

for (int column = 0; column < [keysArray count]; column++) { 

    NSArray *rowArray = [keysArray objectAtIndex:column]; 

    for (int row = 0; row < [rowArray count]; row++) {   
     UIButton *keyButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
     keyButton.frame = CGRectMake(column*kKeyGap, row*kKeyGap, kKeySize, kKeySize); 

     [keyButton setImage:[rowArray objectAtIndex:row] forState:UIControlStateNormal]; 
     [keyButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; 

     [self.view addSubview:keyButton]; 
    } 
} 

を、ネストされたメッセージの表現は、時にはクールにすることができ、 objectAtIndex:への呼び出しのネストはおそらく決して良い考えではありません。

0

テストimages

1

内のオブジェクトの数は、ちょうどオブジェクトがその配列中に存在する場合、あなたはそれで何かをしようとする前に、

- (void)displayImages:(NSMutableArray *)images { 

NSMutableArray *keysArray = [[NSMutableArray alloc] initWithCapacity:5]; 

for (int column = 0; column < 5; column++){ 
    [keysArray addObject:[NSMutableArray arrayWithCapacity:5]]; 
    for (int row = 0; row < 4; row++) { 
     //test to see if there's an object left in the inner array 
     if ([images count] > 0) { 
      [[keysArray objectAtIndex:column] addObject:[images objectAtIndex:0]]; 
      [images removeObjectAtIndex:0]; 
     } 
    } 
}