views:

376

answers:

2
 self.myArray = [NSArray arrayWithObjects: [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil], [NSArray arrayWithObjects: [self generateMySecretObject], [self generateMySecretObject],nil],nil]; 

 for (int k=0; k<[self.myArray count]; k++) {
  for(int s = 0; s<[[self.myArray objectAtIndex:k] count]; s++){
   [[[self.myArray objectAtIndex:k] objectAtIndex:s] setAttribute:[self generateSecertAttribute]];
  }
 }

As you can see this is a simple 2*2 array, but it takes me lots of code to assign the NSArray in very first place, because I found that the NSArray can't assign the size at very beginning. Also, I want to set attribute one by one. I can't think of if my array change to 10*10. How long it could be. So, I hope you guys can give me some suggestions on shorten the code, and more readable. thz

(Some Assumptions: myArray will have a fixed size. It won't grown up or become smaller in the run time.)

+1  A: 

Generate the array by -addObject:.

NSMutableArray* myArray = [NSMutableArray array];
for (int k = 0; k < 10; ++ k) {
  NSMutableArray* subArr = [NSMutableArray array];
  for (int s = 0; s < 10; ++ s) {
    id item = (s == 0 && k == 0) ? [self d] : [self generateMySecretObject];
    [item setAttribute:[self generateSecertAttribute]];
    [subArr addObject:item];
  }
  [myArray addObject:subArr];
  // use [myArray addObject:[[subArr copy] autorelease]] for deep immutability.
}
return [[myArray copy] autorelease];

(Don't query self.myArray many times. Each corresponds to an ObjC call and while someone calls an ObjC call is cheap, it's still not free.)

KennyTM
NSMutableArray is better than NSArray? My 2D array is a fixed size. I think NSArray is more suitable
Tattat
@Tattat: See update for getting an immutable array. You have to create some immutable structures first, it maybe an NSMutableArray or `id[10][10]` etc.
KennyTM
I am afraid of using NSMutableArray, because it don't provide count, objectAtIndex, these kind of method. I am familiar with these method.
Tattat
@Tattat: `NSMutableArray` inherits from `NSArray`, so anything `NSArray` does, `NSMutableArray` does too.
Williham Totland
A: 

If the array is a fixed size and each row is the same length then you could uses a 1D array and an offset, EG:

int rowLength = 5;
int rowNumber = 0;
int columnNumber = 3;

[myArray objectAtIndex: (rowLength * rowNumber) + columnNumber];
Benedict Cohen