Это самый простой и быстрый способ перемешивания NSArrays или NSMutableArrays.
(object puzzles - это NSMutableArray, он содержит объекты головоломки. Я добавил в
индекс переменной объекта головоломки, который указывает начальную позицию в массиве)
int randomSort(id obj1, id obj2, void *context ) {
// returns random number -1 0 1
return (random()%3 - 1);
}
- (void)shuffle {
// call custom sort function
[puzzles sortUsingFunction:randomSort context:nil];
// show in log how is our array sorted
int i = 0;
for (Puzzle * puzzle in puzzles) {
NSLog(@" #%d has index %d", i, puzzle.index);
i++;
}
}
вывод журнала:
#0 has index #6
#1 has index #3
#2 has index #9
#3 has index #15
#4 has index #8
#5 has index #0
#6 has index #1
#7 has index #4
#8 has index #7
#9 has index #12
#10 has index #14
#11 has index #16
#12 has index #17
#13 has index #10
#14 has index #11
#15 has index #13
#16 has index #5
#17 has index #2
вы также можете сравнить obj1 с obj2 и решить, что вы хотите вернуть
Возможные значения:
- NSOrderedAscending = -1
- NSOrderedSame = 0
- NSOrderedDescending = 1