我一直试图将这些结果暂时解决..我似乎无法弄明白。任何人都知道如何做到这一点?
我正在尝试从数组的开头到结尾,按顺序将两个对象相互比较。
Tilo的解决方案:
for (int i=1; i<[tempRightArray count]; i++) {
UIImageView* letterA = [tempRightArray objectAtIndex:i-1];
UIImageView* letterB = [tempRightArray objectAtIndex:i];
NSLog(@"LetterA: %@",letterA);
NSLog(@"LetterB: %@",letterB);
//Distance between right side of Touched piece and Left side of new piece == Touch on Right
CGPoint midPointRightSidePiece = CGPointMake(CGRectGetMaxX(letterA.frame), CGRectGetMidY(letterA.frame));
CGPoint midPointLeftSidepiece = CGPointMake(CGRectGetMinX(letterB.frame), CGRectGetMidY(letterB.frame));
CGFloat distance = DistanceBetweenTwoPoints(midPointLeftSidepiece, midPointRightSidePiece);
NSLog(@"Distance: %f",distance);
}
更新了Pauls块解决方案:
[tempRightArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (idx > 0) {
UIImageView *letterB = (UIImageView*)obj;
id obj2 = [tempRightArray objectAtIndex:--idx]; // idx is the index of obj again given to you by the block args
UIImageView *letterA = (UIImageView*)obj2;
NSLog(@"LetterA: %@",letterA);
NSLog(@"LetterB: %@",letterB);
//Distance between right side of Touched piece and Left side of new piece == Touch on Right
CGPoint midPointRightSidePiece = CGPointMake(CGRectGetMaxX(letterA.frame), CGRectGetMidY(letterA.frame));
CGPoint midPointLeftSidepiece = CGPointMake(CGRectGetMinX(letterB.frame), CGRectGetMidY(letterB.frame));
CGFloat distance = DistanceBetweenTwoPoints(midPointLeftSidepiece, midPointRightSidePiece);
NSLog(@"Distance: %f",distance);
}
}];
答案 0 :(得分:2)
for (int i=1; i<[myArray count]; i++) {
id obj1 = [myArray objectAtIndex:i-1];
id obj2 = [myArray objectAtIndex:i];
[self compare:obj1 to:obj2];
}
答案 1 :(得分:2)
这样的事情怎么样?
NSArray *array = [NSArray arrayWithObjects:@"a", @"b", @"b", @"c", @"d", nil];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (idx > 0) {
// obj = the current element in the array. Given to you by the block args
id obj2 = [array objectAtIndex:--idx]; // idx is the index of obj again given to you by the block args
// Do whatever comparison you want between obj and obj2
// ...
}
}];
不要被语法吓到它非常简单。当前对象为obj
,数组中该对象的索引为idx
。
答案 2 :(得分:0)
启动for循环,索引为1。当索引大于或等于数组计数时停止。比较index和index - 1处的项目;
答案 3 :(得分:0)
for (i = 0; i < array_count - 1; i++) {
x = array[i];
y = array[i + 1];
/* do something with x and y */
}
array
是数组,array_count
是array
的长度,x
和y
被声明为与存储的元素相同的类型array
。这是你要的吗?
答案 4 :(得分:0)
不要忘记Objective-C是C的超集。你可以在C中做任何事情,你仍然可以在Obj-C中做。
您可能不知道comma operator。您可以在for(;;)
循环的每个子句中执行多个操作。
NSUInteger limit, i, j;
for(limit = [array count], i = 0, j = 1; j <= limit; i++, j++)
{
// i and j will increment until j hits the limit.
// do whatever you want with [array objectAtIndex:i] and [array objectAtIndex:j] in here.
}