是否有更好的方法来初始化objective-c中的二维数组:
NSNumber *a = [[NSNumber alloc] initWithInt:0];
NSNumber *b = [[NSNumber alloc] initWithInt:1];
NSMutableArray *template = [[NSMutableArray alloc] initWithCapacity:16];
switch (myInt) {
case 0:
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, a, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, a, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, a, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, a, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
[template addObject:[[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil]];
break;
/* more */
}
答案 0 :(得分:0)
我无法在阵列中找到规律性。至少你可以将一些代码包装成循环
id obj = [[NSArray alloc] initWithObjects:b, b, b, b, b, b, b, b, nil];
for (int i = 0; i<9; ++i){
[template addObject: obj];
}
答案 1 :(得分:0)
假设你想制作一个NSNumber的二维数组
const int templateContent[][8] = { // put your data to this array
1, 1, 1, 1, 1, 1, 1, 1,
1, 0, 1, 1, 1, 1, 1, 1,
// more...
};
const int dim = sizeof(templateContent)/sizeof(int[8]);
NSNumber *numbers[2]; // assume your only need two numbers
for (int i = 0; i < sizeof(numbers)/sizeof(id); i++) {
numbers[i] = [NSNumber numberWithInt:i];
}
NSMutableArray *template = [[NSMutableArray alloc] initWithCapacity:16];
for (int i = 0; i < dim; i++) {
[template addObject:[NSArray arrayWithObjects:
numbers[templateContent[i][0]],
numbers[templateContent[i][1]],
numbers[templateContent[i][2]],
numbers[templateContent[i][3]],
numbers[templateContent[i][4]],
numbers[templateContent[i][5]],
numbers[templateContent[i][6]],
numbers[templateContent[i][7]], nil]];
}
答案 2 :(得分:0)
使用nsdictionary来保存数字,然后将字典存储在nsarray
中