iOS DeveloperiOS 从零 --> RactNative

关于iOS for ... in 注意的地方

2016-11-25  本文已影响53人  鬼丶白

经常我们会筛选一个可变数组里面的元素讲不符合条件的删除掉一般我们的做法:

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"1",@"3",@"2",@"4",@"3",@"2",@"4", nil];
    for (NSString *obj in array) {
        if ([obj isEqualToString:@"2"]) {
            [array removeObject:obj];
        }
    }

这样程序就会抛出个异常如下

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x608000047590> was mutated while being enumerated.'

程序闪退~~

解决办法
1.采用for (NSInteger index = 0; index < array.count; index++) 遍历。需要注意下面4个类型在32-bit和64-bit下的长度区别

size_t type1 = sizeof(int);
size_t type2 = sizeof(long);
size_t type3 = sizeof(float);
size_t type4 = sizeof(double);
32-bit下:4, 4, 4, 8 64-bit下:4, 8, 4, 8

(PS: 这个结果随编译器,换其他平台可不一定)它们的长度变化可能并非我们对64-bit长度加倍的预期,所以说,程序中出现sizeof
的代码多看两眼。而且,除非你明确知道自己在做什么,应该使用下面的类型代替基本类型:
int -> NSInteger
unsigned -> NSUInteger
float -> CGFloat
动画时间 -> NSTimeInterval

上一篇 下一篇

猜你喜欢

热点阅读