user2679041
user2679041

Reputation: 251

conditional if on import for objective c

I would like to use conditional if on import for objective c, didn't see any API for this and wanted to know if this is possible. (this is for adding an import only for a specific IOS) so far I saw this check but it's only for the code, not at the import stage Thanks

if (@available(iOS 11, *)) {
    // Use iOS 11 APIs.
} else {
    // Alternative code for earlier versions of iOS.
}

Upvotes: 4

Views: 2719

Answers (3)

skaak
skaak

Reputation: 3018

You could use one of the foundation framework version numbers, like so.

#ifdef NSFoundationVersionNumber_iOS_8_0
#import "this.h"
#else
#import "that.h"
#endif

or even

#if NSFoundationVersionNumber > 10
#import "this.h"
#else
#import "that.h"
#endif

This is a bit different to the @available that you mention, which checks at runtime. This will check on compile time and depend on your target iOS and it seems it is no longer kept up to date, but worth a try if your requirement is compile time.

Upvotes: 2

Sulthan
Sulthan

Reputation: 130112

There is no reason not to import headers. Importing headers and using functionality contained inside them is a different thing.

You can import headers if they are accessible during compilation. You only have to check for iOS version before using classes and functions inside them.

Checking platform before importing is common only if you want your code to be compiled on different platforms, e.g. iOS and MacOS, which have completely different headers.

Upvotes: 1

Paulw11
Paulw11

Reputation: 114965

You can't, because the #import is a compiler pre-processor directive - it has an effect when your code is compiled. The version of iOS is only known at run time; when your code executes.

The toolchain knows the minimum level of iOS that your app supports because you tell it through the project settings, but it can't recompile your code based on the iOS version encountered when the code is run.

At run time you can use alternate code paths using the #available test you referred to in your question.

Upvotes: 1

Related Questions