
最近在最版本升级,版本强制更新遇到一个问题,比如我们的版本是1.0.0 如果单纯去除.
并不能达到判断版本高低的效果
系统API提供了一个比较字符串的方法,返回NSComparisonResult枚举值
- (NSComparisonResult)compare:(NSString *)string;
枚举值有三种
typedef NS_CLOSED_ENUM(NSInteger, NSComparisonResult) {
// 当前字符串比传入的字符串小
NSOrderedAscending = -1L,
// 当前字符串和传入的字符串一样大
NSOrderedSame,
// 当前字符串比传入的字符串大
NSOrderedDescending
};
利用系统提供的API很好的解决了版本号比较的问题.
接下来我们来一起看下系统提供的其他的方法
/ *在compare:方法中,range参数指定要在比较中使用的接收器的子范围而不是整体。 范围不适用于搜索字符串。 例如,[@“AB”比较:@“ABC”选项:0范围:NSMakeRange(0,1)]将“A”与“ABC”进行比较,而不是将“A”与“A”进行比较,并返回NSOrderedAscending。 指定超出接收方边界的范围是错误的,并且可能引发异常。
*/
// 无条件比较
- (NSComparisonResult)compare:(NSString *)string;
// 比较(指定字符串,条件)
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
// 比较(指定字符串,条件,范围)
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:
//比较(指定字符串,条件,范围,本地化)
(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice.
// 比较(不区分大小写)
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
// 本地化比较
- (NSComparisonResult)localizedCompare:(NSString *)string;
// 本地化比较(不区分大小写)
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
// 本地化比较(标准)
- (NSComparisonResult)localizedStandardCompare:(NSString *)string API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
- (BOOL)isEqualToString:(NSString *)aString;
NSStringCompareOptions 枚举值
/* These options apply to the various search/find and comparison methods (except where noted).
这些选项适用于各种搜索/查找和比较方法(除非另有说明)。
*/
typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
NSCaseInsensitiveSearch = 1, //不区分大小写比较
NSLiteralSearch = 2, //区分大小写比较
NSBackwardsSearch = 4, //从字符串末尾开始搜索
NSAnchoredSearch = 8, //搜索限制范围的字符串
NSNumericSearch = 64, //按照字符串里的数字为依据,算出顺序
NSDiacriticInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 128, //忽略 "-" 符号的比较
NSWidthInsensitiveSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 256,//忽略字符串的长度,比较出结果
NSForcedOrderingSearch API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)) = 512, //忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending
NSRegularExpressionSearch API_AVAILABLE(macos(10.7), ios(3.2), watchos(2.0), tvos(9.0)) = 1024 /只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比较方法,如果设置此项,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
};
网友评论