iOS数字比较问题

1.问题描述:

从服务器拉取一组视频数据, 循环播放
问题出现在, 比较当前播放的index和数组个数
结果, 当前播放的index总比数组个数大

2.代码

@property (nonatomic, assign) NSInteger currentShowIndex;
@property (nonatomic, strong) NSArray  *arrModels;
/// 切换到下一次
- (void)actionStartShowNext {
    if (_currentShowIndex >= _arrModels.count - 1) {
        _currentShowIndex = -1;
        [self configData];
        return;
    }
    _currentShowIndex += 1;
}

3.解决

NSArray的count是NSUInteger, 我定义的currentShowIndex是NSInteger
无符号类型与有符号类型进行基础运算,如加减乘除,比较大小时,无符号类型会被自动转换为有符号类型

/// 切换到下一次
- (void)actionStartShowNext {
    if (_currentShowIndex >= (NSInteger)(_arrModels.count - 1)) {
        _currentShowIndex = -1;
        [self configData];
        return;
    }
    _currentShowIndex += 1;
}

参考:
https://stackoverflow.com/questions/21847459/ios-compare-nsuinteger-to-nsinteger

你可能感兴趣的:(iOS数字比较问题)