【iOS】比较版本号大小算法

2017-12-21  本文已影响0人  Teun丶

实现如下:

/**
 比较本地版本和最新版本号的大小

 @param lastVersionStr 最新版本,例:1.0.7或者2.0.2.11
 @return 如果本地版本<最新版本,返回1,否则返回0
 */
- (BOOL)compareLastVersion:(NSString *)lastVersionStr{
    //从info.plist文件获取Version
    NSString *version = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    //本地版本号
    NSInteger localVersion = [[version stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
    //最新版本号
    NSInteger lastVersion = [[lastVersionStr stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
    //处理版本号缩减为两位
    lastVersion = lastVersion<100?lastVersion*=10:lastVersion;
    
    return localVersion<lastVersion?1:0;
}

使用如下:

    //1.输入版本号 1.3.0
    BOOL result = [self compareLastVersion:@"1.3.0"];
    if (result == 1) {
        NSLog(@"检测有新版本,赶紧更新吧大爷!");
    }else{
        NSLog(@"还JB不升级");
    }

注意点:尽量保持本地版本号和输入版本号段数一致

上一篇 下一篇

猜你喜欢

热点阅读