Tim*_*aev 3 random shuffle objective-c nsmutablearray
如何获取NSMutableArray的随机索引而不重复?我有NSMutableArray*audioList.我想以随机模式播放每首曲目,而不重复.如何以最好的方式做到这一点?
请参阅以下代码:
int length = 10; // int length = [yourArray count];
NSMutableArray *indexes = [[NSMutableArray alloc] initWithCapacity:length];
for (int i=0; i<10; i++) [indexes addObject:[NSNumber numberWithInt:i]];
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:length];
while ([indexes count])
{
int index = rand()%[indexes count];
[shuffle addObject:[indexes objectAtIndex:index]];
[indexes removeObjectAtIndex:index];
}
[indexes release];
for (int i=0; i<[shuffle count]; i++)
NSLog(@"%@", [shuffle objectAtIndex:i]);
Run Code Online (Sandbox Code Playgroud)
现在在shuffle中你将拥有你的数组的索引而不重复.
希望对你有帮助
| 归档时间: |
|
| 查看次数: |
3232 次 |
| 最近记录: |