我有NSMutableArray
。我使用for循环检查数组1中的每个项目并删除当前项目。然后我想把下一个索引项放到第一个索引中。就像
数组= 1,2,3,4,5,6
数组= 3,4,5,6
我使用for循环删除索引。如何将下一个元素移动到删除的索引位置
已更新
for (int i=0; i<[m3u8 count]; i++) {
NSString *str=[NSString stringWithFormat:
@"http://cp2.comci.com:1000/server/default.stream/%@",
[mutArrayMP3files objectAtIndex:i]
];
[audioPlayer queue:str];
[mutArrayMP3files removeObjectAtIndex:i];
// Then here I want to make that array a continous one.
// Let's say it removed object at index 0, then 1st object should move to 0th location,
// 2nd should move to 1st.... likewise
}
答案 0 :(得分:-1)
当你在迭代它时,你无法修改NSMutableArray。如果你在循环时缩小数组,那么你就不能继续增加你使用的索引,否则你将会跑到最后。最终。你能做的就是复制并修改它;或者,使用while
循环而不是迭代器:
NSMutableArray *array = @{@1, @2, @3, @5, @6};
while([array count]) {
NSNumber firstElement = [array firstObject];
// do something with firstElement;
[array removeObjectAtIndex:0];
}
您当前代码的问题在于您最终会尝试使用索引超出范围来引用数组中的项目,因为随着时间的推移,数组会越来越小。以下是如何使用更接近OP的代码调整它:
// assumes [m3u8 count] equals original size of mutArrayMP3files
for (int i=0; i<[m3u8 count]; i++) {
NSString *str=[NSString stringWithFormat:
@"http://cp2.comci.com:1000/server/default.stream/%@",
// this line would have crashed:
// [mutArrayMP3files objectAtIndex:i]
[mutArrayMP3files objectAtIndex:0]
];
[audioPlayer queue:str];
// this line would also have crashed
// [mutArrayMP3files removeObjectAtIndex:i];
// remove the object that was processed, all other objects "shift down" one index
[mutArrayMP3files removeObjectAtIndex:0];
}