Ios 将NSArray的下半部分与上半部分交错

Ios 将NSArray的下半部分与上半部分交错,ios,objective-c,algorithm,sorting,nsmutablearray,Ios,Objective C,Algorithm,Sorting,Nsmutablearray,我有一个NSMutableArray包含十个按特定顺序排列的自定义对象 我需要的是重新排列对象,使数组的后半部分与前半部分交错: 之前:1、2、3、4、5、6、7、8、9、10 之后:1,6,2,7,3,8,4,9,5,10 我如何才能做到这一点? (void)exchangeObjectAtIndex:(nsInteger)idx1与ObjectAtIndex:(nsInteger)idx2 (无效)排序比较:(NSComparator)cmptr 你要找的是所谓的洗牌(想想洗牌一副牌-相同的

我有一个
NSMutableArray
包含十个按特定顺序排列的自定义对象

我需要的是重新排列对象,使数组的后半部分与前半部分交错:

之前:1、2、3、4、5、6、7、8、9、10
之后:1,6,2,7,3,8,4,9,5,10

我如何才能做到这一点?

  • (void)exchangeObjectAtIndex:(nsInteger)idx1与ObjectAtIndex:(nsInteger)idx2

  • (无效)排序比较:(NSComparator)cmptr


你要找的是所谓的
洗牌(想想洗牌一副牌-相同的数据,不同的顺序)。以下方法可用于

在修改数组时不能对其进行枚举,我也不想在数组的元素上循环。相反,创建一个带有索引的for循环,并用于生成第二个交换索引

for (NSUInteger n = 0; n < array.count; n++) {
    NSUInteger m = arc4random_uniform(array.count);
    [array exchangeObjectAtIndex:n withObjectAtIndex:m];
}

为什么不创建第二个NSArray,在其中按您想要的顺序放置您的值?之后,如果希望使用第一个数组,则从中删除所有项

[firstArray removeAllObjects];
然后将项目从第二个数组中放回:

for (int i = 0; i < [secondArray count]; i++)
{
[firstArray addObject: [secondArray objectAtIndex:i]];
}
for(int i=0;i<[secondArray count];i++)
{
[firstArray addObject:[secondArray objectAtIndex:i]];
}

为什么不像这样简单:NSArray*arr=@[Object 1、Object 2、Object 3、Object 4、Object 5、Object 6、Object 7、Object 8、Object 9、Object 10];=>NSArray*结果=@[arr[0]、arr[5]、arr[1]、arr[6]、arr[2]、arr[7]、arr[3]、arr[8]、arr[4]、arr[9];
[firstArray removeAllObjects];
for (int i = 0; i < [secondArray count]; i++)
{
[firstArray addObject: [secondArray objectAtIndex:i]];
}