1,代码为:
NSMutableArray *array = [NSMutableArray array];
[array addObject:@" "];
[array addObject:@" "];
[array addObject:@" "];
[array removeObjectAtIndex:5];
崩溃为:
Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM removeObjectsInRange:]: range {5, 1} extends beyond bounds [0 .. 2]'
解析:数字5是removeObjectAtIndex的下标,[0 .. 2]是数组里有从0到2一共3个元素。
解决办法:
- (void)removeObjectAtSafeIndex:(NSUInteger)index
{
if (index < self.count)
{
[self removeObjectAtIndex:index];
}
}
方法写成类目,然后调用这个方法移除元素
2,代码为:
NSMutableArray *array = [NSMutableArray array];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 1000; i++) {
[array addObject:@"1"];
NSLog(@"%d",i);
}
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
for (int i = 0; i < 100; i++) {
for (NSString *str in array) {
NSLog(@"%@",str);
}
/*for (int i = 0; i < array.count; i++) {
NSLog(@"%@",array[i]);
}*/
/*[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%@",obj);
}];*/
}
});
崩溃为:
Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x17004e670> was mutated while being enumerated.'
解析:用for in 进行遍历其间如果修改了数组(增加或删除元素)会引起闪退
解决:用array.copy来遍历或用注释中的两种方式