6

How can you check if a constant is set at runtime? For instance, in iOS 4, UIApplicationDidEnterBackgroundNotification is available, but when running on iOS 3 it will through an error if you try to use it.

David Beck
  • 10,099
  • 5
  • 51
  • 88

1 Answers1

12

You should probably look at this other question, which in my opinion also answers yours. if (&UIApplicationWillEnterForegroundNotification != NULL) should be dynamic-linking-safe and tell you whether the constant exists or not.

Community
  • 1
  • 1
Romain
  • 12,679
  • 3
  • 41
  • 54
  • If you are using LLVM, you have to do some tricks to get it to not optomize out your if statement. This works for me. BOOL backgroundOK = &UIApplicationDidEnterBackgroundNotification != NULL; if (backgroundOK) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification bject:nil]; } – David Beck Jul 05 '10 at 15:04
  • Has this optimizer bug been already fixed in LLVM/Clang compiler? In which version? – Nikita Zhuk Apr 20 '11 at 13:14
  • It's not a bug in LLVM, but a feature. LLVM will optimize out statements with no side-effect and it is good. But it makes stuff a bit tougher for this type of code. – Romain Apr 21 '11 at 18:47
  • Why not using `#ifdef`? – Iulian Onofrei Oct 29 '14 at 11:57
  • @IulianOnofrei because UIApplicationWillEnterForegroundNotification is not a macro... – Romain Dec 03 '14 at 13:39