Search code examples
objective-cnsnumbernsnumberformatterinfo.plist

Convert CFBundleVersion to NSNumber & compare it


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?


Solution

  • 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.