sen*_*rio 0 refactoring objective-c nsarray
我有这样的指示:
[self someMethod:CGPointMake(50, 50)];
[self someMethod:CGPointMake(270, 50)];
[self someMethod:CGPointMake(50, 360)];
[self someMethod:CGPointMake(270, 360)];
...
Run Code Online (Sandbox Code Playgroud)
我想使用NSArray重构代码,如下所示:
NSArray items = [NSArray initWithObjects:
CGPointMake(50, 50),
CGPointMake(270, 50),
CGPointMake(50, 360),
CGPointMake(270, 360),
...
nil];
Run Code Online (Sandbox Code Playgroud)
我不知道正确的语法,有人可以帮助我吗?我试过这个,但XCode告诉我"Selector元素类型CGPoint不是一个有效的对象":
CGPoint point = [CGPoint alloc];
for (point in items) {
[self someMethod:point];
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
*我的个人结构拳击宏:
#define STRUCT_BOX(x) [NSValue valueWithBytes:&x objCType:@encode(typeof(x))];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1227 次 |
| 最近记录: |