简体   繁体   中英

Why preprocessor directives not working

I'm trying to create variable for the device as per the version but my control is always going to the else part. My iOS is 9.3

#if os(iOS) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
    var addressBookRef : CNContactStore? = nil
#else
    var addressBookRef : ABAddressBook? = nil
#endif

I've also tried this as suggested here but defined not taking in Swift2.x

#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
    var addressBookRef : CNContactStore? = nil
#else
    var addressBookRef : ABAddressBook? = nil
#endif

When I'm checking at the run time and using breakpoints, I can see that my control always going to else portion and variable addressBookRef is of type ABAddressBook .

Suggest please what wrong I'm doing

You cannot check the version of iOS with a directive, you need to check this at runtime.

If you are using iOS 8.0 or later you can use this:

let os = NSProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (8, 0, _):
    // 8.0.0 and < 8.1.0
case (8, _, _):
    // 8.1.0 and < 9.0
case (9, _, _):
    // 9.0.0
default:
    //
}

You can also use UIDevice.currentDevice().systemVersion which will also work on iOS 7:

switch UIDevice.currentDevice().systemVersion.compare("8.0.0", options: NSStringCompareOptions.NumericSearch) {
case .OrderedSame, .OrderedDescending:
    // >= 8.0
case .OrderedAscending:
    // < 8.0
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM