在nsmutable Array objective c中的shuffle objectindex

时间:2017-12-11 12:17:37

标签: objective-c

我想在NSMutableArray中将我的整个ObjectIndex混乱。

例如,如果我的JSON应该是这样的:

[{@"name":@"Vikas" , @"Id":@"1",@"subject":@"english"},
{@"Name":@"Rajat",@"Id":@"2",@"Subject":@"Math"},
{@"Name":@"Jhon",@"id":@"3",@"Science"}]

我希望结果应该是这样的:

[{@"Name":@"Jhon",@"id":@"3",@"Science"},
{@"Name":@"Rajat",@"Id":@"2",@"Subject":@"Math"},
{@"name":@"Vikas" , @"Id":@"1",@"subject":@"english"}]

我想要改变整个对象,但我无法在Objective-C中执行此操作。

- (void)shuffle
{
    NSUInteger count = [self count];
    if (count <= 1) return;
    for (NSUInteger i = 0; i < count - 1; ++i) {
        NSInteger remainingCount = count - i;
        NSInteger exchangeIndex = i + arc4random_uniform((u_int32_t )remainingCount);
        [self exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
    }
}

这是我的代码。我不知道我哪里错了。如果有人知道那么请告诉我。

2 个答案:

答案 0 :(得分:0)

在NSMutableArray上创建类别:

@interface NSMutableArray (Shuffle)
- (void)shuffle;
@end

@implementation NSMutableArray (Shuffle)
- (void)shuffle {
    for (NSInteger i = self.count-1; i > 0; i--)
    {
        [self exchangeObjectAtIndex:i withObjectAtIndex:arc4random_uniform((uint32_t)i+1)];
    }
}
@end

随机播放你的可变阵列:

NSMutableArray *t = [@[@{@"Name":@"Vikas", @"Id":@"1", @"Subject":@"English"},
                      @{@"Name":@"Rajat", @"Id":@"2", @"Subject":@"Math"},
                      @{@"Name":@"John", @"Id":@"3", @"Subject":@"Science"}] mutableCopy];
[t shuffle];

答案 1 :(得分:-2)

我们有exchangeObjectAtIndex:withObjectAtIndex:已经存在。充分利用它,并以您想要交换的方式编写逻辑。