Для цикла, который даст мне объекты с индексом: 0,1, затем 1,2, затем 2,3, а затем 3,4, следуя этому шаблону до подсчета массива? - PullRequest
0 голосов
/ 30 октября 2011

Я уже некоторое время пытаюсь получить эти результаты ... Кажется, я не могу этого понять. Кто-нибудь знает, как это сделать?

Я пытаюсь сравнить два объекта друг с другом от начала моего массива до конца в этой последовательности.

Решение Тило:

        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);

        }

Обновлено с блочным решением Паулса:

    [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);

        }

    }];

Ответы [ 5 ]

2 голосов
/ 30 октября 2011

Как насчет этого?

  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 голосов
/ 30 октября 2011
for (int i=1; i<[myArray count]; i++) {
  id obj1 = [myArray objectAtIndex:i-1];
  id obj2 = [myArray objectAtIndex:i];

  [self compare:obj1 to:obj2];
}
0 голосов
/ 30 октября 2011

Не забывайте, что Objective-C является надмножеством C. Все, что вы можете делать в C, вы можете делать в Obj-C.

Возможно, вы не знали о оператор запятой .Вы можете выполнить несколько операций в каждом предложении цикла 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.
  }
0 голосов
/ 30 октября 2011
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. Это то, что вы просите?

0 голосов
/ 30 октября 2011

Запустите цикл for с вашим индексом в единицу.Остановить, когда индекс больше или равен количеству массивов.Сравнить элемент по индексу и по индексу - 1;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...