1

我正在尝试对 NSMutableArray 进行洗牌,以便每次有人加载视图时它的顺序都会混淆。

在我的-(void)viewDidLoad我把下面的代码(如其他用户的建议):

NSMutableArray *shuffleTwo = [self.chosenTeamDict objectForKey:@"clubs"];

int random = arc4random() % [shuffleTwo count]; 
for (int i = 0; i < [shuffleTwo count]; i++) {
    [shuffleTwo exchangeObjectAtIndex:random withObjectAtIndex:i]; 
}

NSLog(@"%@", shuffleTwo);

但是当我这样做并尝试运行该页面时,我收到以下错误:

2012-07-09 18:42:16.126 Kit-Quiz[6505:907] (null)
libc++abi.dylib: terminate called throwing an exception

谁能建议一种改组这个数组的新方法,或者建议我如何避免这个错误..!?我正在为 iOS 5 构建,我正在使用 Xcode45-DP1。提前致谢!

(编辑)

我也试过这个方法,我得到了同样的错误:

NSMutableArray *shuffledArray = [[NSMutableArray alloc] init];
    NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:@"clubs"];

    for(int s = 0; s < [standardArray count]; s++){
        int random = arc4random() % s;
        [shuffledArray addObject:[standardArray objectAtIndex:random]];
    }

    NSLog(@"%@", shuffledArray);
4

3 回答 3

1

试试 Fisher-Yates 洗牌。它是这样的:

int count = shuffledArray.count;

for(int i=count; i>0; i--) {

 int j = arc4random_uniform(count);

 [shuffledArray exchangeObjectAtIndex:j withObjectAtIndex:i];

}

确保您的数组不是零并且所有条目都是分配的对象:)

资料来源:Fisher-Yates Shuffle

于 2012-07-09T18:34:39.310 回答
1
NSMutableArray *standardArray = [self.chosenTeamDict objectForKey:@"clubs"];

int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[shuffledArray objectAtIndex:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
    int index = rand()%[indexes count];
    [shuffle addObject:[indexes objectAtIndex:index]];
    [indexes removeObjectAtIndex:index];
}
for (int i=0; i<[shuffle count]; i++) NSLog(@"%@", [shuffle objectAtIndex:i]);

NSLog(@"%@", shuffle);

^^ 回答

于 2012-07-09T20:05:06.377 回答
0

首先,您确实应该启用异常断点。在左侧面板的 XCode 中,单击断点选项卡,单击左下角的“+”号 -> 异常断点 -> 完成。

我怀疑你的问题出在这里:

int random = arc4random() % [shuffleTwo count]; 

如果 [shuffleTwo count] 的计算结果为零(如果 shuffleTwo 为 nil),它将引发除以零异常。编辑:在 Objective-C 中似乎并非如此。

于 2012-07-09T18:17:39.413 回答