使用NSArray的“for x in”语法

时间:2012-12-23 03:45:29

标签: objective-c refactoring nsarray

我有这样的指示:

[self someMethod:CGPointMake(50, 50)];
[self someMethod:CGPointMake(270, 50)];
[self someMethod:CGPointMake(50, 360)];
[self someMethod:CGPointMake(270, 360)];
...

我想使用NSArray重构代码,如下所示:

NSArray items = [NSArray initWithObjects:
                  CGPointMake(50, 50),
                  CGPointMake(270, 50),
                  CGPointMake(50, 360),
                  CGPointMake(270, 360),
                  ...
                  nil];

我不知道正确的语法,有人可以帮助我吗?我试过这个,但是XCode告诉我“Selector元素类型CGPoint不是一个有效的对象”:

CGPoint point = [CGPoint alloc];

for (point in items) {
    [self someMethod:point];
}

2 个答案:

答案 0 :(得分:5)

for-in循环是一个Objective-C概念,用于迭代集合类(符合NSEnumeration)。如果您想迭代C-structs(如CGPoints),请使用带有C-array的标准for循环,或将CGPoints包装在NSValues中。

以下是现代Objective-C语法中的重构内容:

NSArray *items = @[
                  [NSValue valueWithPoint:CGPointMake(50, 50)], //wrap the points in an
                  [NSValue valueWithPoint:CGPointMake(270, 50)], //NSValue so they become
                  [NSValue valueWithPoint:CGPointMake(50, 360)], //first class citizens
                  [NSValue valueWithPoint:CGPointMake(270, 360)],//(Y no boxing?*)
                 ]; //End of collection literal
for (NSValue *value in items) { //iterate through the NSValues with our points
    [self someMethod:[value pointValue]]; //'un-wrap' the points by calling -pointValue
}

*我的个人结构拳击宏:

#define STRUCT_BOX(x) [NSValue valueWithBytes:&x objCType:@encode(typeof(x))];

答案 1 :(得分:0)

没有必要求助于NSArray。正如CodaFi所说,“如果你想迭代C-structs(比如CGPoints),请使用带有C-array的标准for循环。”那么,为什么不这样做?

static CGPoint items[] = {
    {50, 50},
    {270, 50},
    {50, 360},
    {270, 360},
};

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

这会在编译时创建数组,而不是运行时!然后迭代数组:

for (NSUInteger i = 0; i < ARRAY_SIZE(items); ++i)
    [self someMethod:items[i]];

有关涉及字典数组的另一个示例,请参阅Objective-C Is Still C (Not Java!)