开发者

How to simplify my code... 2D NSArray in Objective C...?

 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]];
  }
 }
开发者_StackOverflow社区

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.)


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.)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜