Before asking why: I'm writing an extension that observes the CFBundleVersion of an app & then compares it to old version that isn't supported by the extension.

Here's what I do to compare.

CFStringRef _version = CFURLCreateStringByAddingPercentEscapes(NULL,
                                                               (__bridge CFStringRef)[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"],
                                                               NULL,
                                                               (CFStringRef)@" !*'();:@&=+$,/?%#[]",
                                                               kCFStringEncodingUTF8);

NSString *versionString = (NSString *)CFBridgingRelease(_version);

NSNumberFormatter * nsFormatter = [[NSNumberFormatter alloc] init];
[nsFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSNumber * installedVersion = [nsFormatter numberFromString:versionString];
NSNumber * incompatibleVersion = [nsFormatter numberFromString:@"6.1.0"];


if (installedVersion <= incompatibleVersion) {

    NSLog(@"This was triggered");

}

The code works great, but only when there are two decimals. For instance, if I set the CFBundleVersion to 6.0 or 5.0 The code is not triggered. Is there a better way of comparing? I don't understand why it's thinking 5.0 is greater than 6.1.0

Suggestions?

有帮助吗?

解决方案

You obviously can't treat it as one number, so treat it as a set of numbers with a separator. Then, you can use componentsSeparatedByString:@"." and process each of the numbers separately.

Be sure to check the count of the components. If one number has more components than the other you should fall back to default values (0) if you haven't already got a result from the algorithm.

Loop over the components and compare each part.

其他提示

Versions in the format major.minor.patch cannot generally be represented as a single number. It's best to compare the strings using ...

[version1 compare:version2 options:NSNumericSearch];

This only works if the number of components is always the same.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top