0

我试图在没有 NSDictionary 的情况下获得如下所示的列数组。它运作良好。

但我想知道objective-c 文字是否支持此功能。

有这样的文字吗?

例如 array[][0]?、array[*][0]、array[?][0] 等等...?

NSArray *array1 = @[@"AAa", @"BBB", @"CCC"];
NSArray *array2 = @[@"AAb", @"BBB", @"CCC"];
NSArray *array3 = @[@"AAc", @"BBB", @"CCC"];

array = @[array1, array2, array3];

NSArray *result;
result = [self getColumnArray:0]; // <- get array's [*][0]
NSLog(@"result is : %@", result);

result = [self getColumnArray:2]; // <- get array's [*][2]
NSLog(@"result is : %@", result);


- (NSArray *)getColumnArray:(NSUInteger)index {
    NSMutableArray *resultArray = [NSMutableArray array];

    for (NSArray *item in array) {
        [resultArray addObject:item[index]];
    }

    return resultArray;
}


Excuted result :

2012-10-29 16:00:24.550 testButton[28245:11303] result is : (
    AAa,
    AAb,
    AAc
)
2012-10-29 16:00:24.552 testButton[28245:11303] result is : (
    CCC,
    CCC,
    CCC
)
4

2 回答 2

0

是的可能...请参阅解决方案的链接 http://clang.llvm.org/docs/ObjectiveCLiterals.html

于 2012-10-29T07:06:16.763 回答
0

以下代码将起作用:

NSArray *arr = @[ @[@"A", @"B"], @[@"C", @"D"]];
NSLog(@"%@", array[0][0]); // Logs 'A'

因此,您可以执行以下操作来达到您想要的效果:

// Log the 0 element of each NSArray within your primary array.
NSArray *primaryArray = @[ @[@"A", @"1"], @[@"A", @"2"], @[@"A", @"3"] ];
for (int i = 0; i < array.count; i++) {

     NSLog(@"%@", primaryArray[i][0]); // Logs "AAA"

}
// Or you can use a for (NSArray *arr in primaryArray) fast-enumeration loop.

据我所知,没有以下语法:

NSLog(@"%@", primaryArray[*][0]); // Could log "AAA"

有几个原因。

  1. 没有指定primaryArray 的长度。
  2. NSLog 不知道它需要多少%@(其他用途的类似原因,例如你会怎么做return primaryArray[*][0]?)
  3. You are condensing an O(n) process into a single call. This could be forgiven if there was documented API for it.
  4. For this to be possible, the * operator would have to be overloaded (in this case to a 'wildcard' function) and Objective-C does not support operator overloading (except when done inside the compiler, which I suppose is no longer 'operator overloading' but 'adding a language feature'). Also, * already denotes a pointer in C and ? is used in the ?: ternary operator.
  5. Objective-C already has a fast-enumeration structure which handles these situations, if this syntax were to be added, you'd be reinventing the wheel a little.

In short, a fast-enumeration loop is the best way to do what you want, and the nested [i][0] box syntax aids its readability slightly. I agree the wildcard syntax would be very handy in some cases (such as logging and enumeration), but I think it would be too difficult to implement succinctly across the board. Plus, since they overloaded ^ for blocks, they're running out of usable operators!

于 2012-10-29T08:09:31.240 回答