我正在试图改组一个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。提前谢谢!
(适用EDIT)
我也试过这个方法,但我得到了同样的错误:
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);
答案 0 :(得分:1)
尝试Fisher-Yates shuffle。它是这样的:
int count = shuffledArray.count;
for(int i=count; i>0; i--) {
int j = arc4random_uniform(count);
[shuffledArray exchangeObjectAtIndex:j withObjectAtIndex:i];
}
确保您的数组是非零的并且所有条目都是分配的对象:)
答案 1 :(得分: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);
^^ ANSWER
答案 2 :(得分:0)
首先,您确实应该启用异常断点。在左侧面板的XCode中,单击断点选项卡,单击左下角的“+”符号 - &gt;异常断点 - &gt;完成。
我怀疑你的问题在于:
int random = arc4random() % [shuffleTwo count];
如果[shuffleTwo count]的计算结果为零(如果shuffleTwo为nil),它将抛出除零异常。编辑:似乎不是Objective的情况-C。