Literal #YES not working in iOS 5 / Xcode 4.4 - ios

New Xcode 4.4 is out and it should support literals like
#42
#"String"
#23.0L
#{ #"key" : obj } and
#[obj1, obj2]
and it should also support #YES and #NO, which isn't working when targeting latest iOS 5 (and prior).
After compiling it show the error message:
Unexpected type name 'BOOL': expected expression
I know you can fix it by typing #(YES) and #(NO). But I want to know the reason why it isn't working as expected.

The reason is Apple forgot the parentheses here:
#define YES (BOOL)1
This will be fixed in iOS 6 SDK:
#define YES ((BOOL)1)
In the meantime you must type #(YES).

This is useful for information about literals.
A commenter on this answer also points out:
There is one small thing I'd like to warn about. Literal bools are also not supported
because of this. However, a quick fix that I implemented was adding
this to the beginning of one of my common headers (in an iOS project)
#ifndef __IPHONE_6_0
#if __has_feature(objc_bool)
#undef YES
#undef NO
#define YES __objc_yes
#define NO __objc_no
#endif
#endif
#phix23s answer seems to be more to the point. You should accept that.
This was worth adding from comments:
It should be noted that this needs to be done after the #import . If one puts these #defines in their Prefix.pch, they should make sure to import Foundation earlier in the pch

Related

Adopting os_log APIs while keeping backward compatibility

I'm trying to add support for the new logging and activity tracing APIs to a library in a way that maintains backward compatibility for users of the library who haven't yet adopted the latest version of the OS (iOS or macOS). I'm defining custom logging macros for each level of logging, and then for older OSes, falling back to NSLog. I've gotten this working, with one problem.
The new APIs require you to mark any non-constant, non-scalar values as explicitly public if you want them to show up in log output. This is what an invocation of my macro looks like:
UZKLogInfo("Reading file %{public}# from archive", fileName);
This compiles fine with the SDK that includes os_log (e.g. iOS 10.0 or later), but when I compile with an earlier version so my macro falls back to NSLog, I get a compiler warning:
Using 'public' format specifier annotation outside of os_log()/os_trace()
And the log line printed looks like this:
Reading file <decode: missing data> from archive
This is a simplified version of my macro definition (only including the info definition and simplifying the conditional:
#if UNIFIED_LOGGING_SUPPORTED
#import os.log;
#define UZKLogInfo(format, ...) os_log_info(OS_LOG_DEFAULT, format, ##__VA_ARGS__);
#else // Fall back to regular NSLog
#define UZKLogInfo(format, ...) NSLog(#format, ##__VA_ARGS__);
#endif
Is there any way to strip the "{public}" text (some kind of string replacement?) from format in the fallback case? Or is there another way to support the old and new APIs without giving up the level of info I've always shown in the logs? I need to use a macro (according the last year's WWDC session on the topic, or else I lose the call site metadata.
I chose to do an NSString replace in the macro, and to suppress the compiler warnings as part of it, so it could be done for each line, rather than globally for the whole file or project. It looks like this:
#if UNIFIED_LOGGING_SUPPORTED
#import os.log;
#define UZKLogInfo(format, ...) os_log_info(OS_LOG_DEFAULT, format, ##__VA_ARGS__);
#else // Fall back to regular NSLog
#define _removeLogFormatTokens(format) [#format stringByReplacingOccurrencesOfString:#"{public}" withString:#""]
#define _stringify(a) #a
#define _nsLogWithoutWarnings(format, ...) \
_Pragma( _stringify( clang diagnostic push ) ) \
_Pragma( _stringify( clang diagnostic ignored "-Wformat-nonliteral" ) ) \
_Pragma( _stringify( clang diagnostic ignored "-Wformat-security" ) ) \
NSLog(_removeLogFormatTokens(format), ##__VA_ARGS__); \
_Pragma( _stringify( clang diagnostic pop ) )
#define UZKLogInfo(format, ...) _nsLogWithoutWarnings(format, ##__VA_ARGS__);
#endif
It's called like so:
UZKLogInfo("Message: %#", anObjectToLog);

Preprocessor macro for Apple Watch?

I was looking at Apple's Lister (for Apple Watch, iOS, and OS X) sample. The sample performs a test for iOS and OS X:
#import <TargetConditionals.h>
#if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
#import ListerKit;
#elif TARGET_OS_MAC
#import ListerKitOSX;
#endif
However, there is no test for TARGET_OS_WATCH or similar. Grepping for watch in TargetConditionals.h delivers no hits:
$ cat /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer
/SDKs/iPhoneOS7.1.sdk/usr/include/TargetConditionals.h | grep -i watch
$
From TargetConditionals.h, I know there are:
These conditionals specify in which Operating System the generated code will
run. The MAC/WIN32/UNIX conditionals are mutually exclusive. The EMBEDDED/IPHONE
conditionals are variants of TARGET_OS_MAC.
TARGET_OS_MAC - Generate code will run under Mac OS
TARGET_OS_WIN32 - Generate code will run under 32-bit Windows
TARGET_OS_UNIX - Generate code will run under some non Mac OS X unix
TARGET_OS_EMBEDDED - Generate code will run under an embedded OS variant
of TARGET_OS_MAC
TARGET_OS_IPHONE - Generate code will run under iPhone OS which
is a variant of TARGET_OS_MAC.
TARGET_IPHONE_SIMULATOR - Generate code for running under iPhone Simulator
Question: Is there a preprocessor for Apple's watch?
I'm tagging with ios, but I'm not sure that's the correct OS for this question.
The list below was compiled from iPhone's TargetConditionals.h. The Simulator and OS X are similar (they just have different bits set to 1):
#define TARGET_OS_MAC 1
#define TARGET_OS_WIN32 0
#define TARGET_OS_UNIX 0
#define TARGET_OS_EMBEDDED 1
#define TARGET_OS_IPHONE 1
#define TARGET_IPHONE_SIMULATOR 0
Questions: Does the watch use TARGET_OS_EMBEDDED? Does the watch omit TARGET_OS_IPHONE?
You can find all kind of target conditionals in the TargetConditionals.h (cmd + shift + o and type TargetConditionals.h).
In this list you can find a list like this and many more useful defines.
Currently it does contain TARGET_OS_WATCH since WatchOS 2. For WatchOS 1 it was not possible to run custom code on the watch so it was not needed back then since everything ran on the phone itself.
#define TARGET_OS_MAC 1
#define TARGET_OS_WIN32 0
#define TARGET_OS_UNIX 0
#define TARGET_OS_IPHONE 1
#define TARGET_OS_IOS 0
#define TARGET_OS_WATCH 1
#define TARGET_OS_TV 0
#define TARGET_OS_SIMULATOR 0
#define TARGET_OS_EMBEDDED 1
Swift Addition
#if os(watchOS)
[Watch code]
#else
[Code for iOS, appleTV, or any else clause]
#endif
Some other valid values: iOS, OSX, tvOS
A small explanation about this and more http://nshipster.com/swift-system-version-checking/
At the bottom of this document
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-XID_15#Build Configurations
Under the section 'Build Configurations' you can find a (hopefully) up to date list with all these values that are currently available
As of watchOS 2.0, you can run native code on the watch, so this is a more relevant question.
I'm using the first early beta of watchOS 2, so this may change, but right now, TARGET_OS_WATCH is set to 1 on watchOS.
(Also, be careful: TARGET_OS_IPHONE is also set to 1 on watchOS, though TARGET_OS_IOS is 0.)
There is no WatchKit or app extension target conditional. But you can create your own per-target conditionals that you use in the same way.
If you look in the "Build Settings" section for any target, there's a section called "Other C Flags". Add an entry for the WatchKit target. If you add something like -DMY_WATCHKIT_FLAG=1, you can then do #if MY_WATCHKIT_FLAG in code.
Make your custom flag, well, custom. It's not impossible that Apple might add a flag in the future called something like TARGET_WATCH_APP or whatever. Use a prefix on the flag name to make it specific to you.
With the current WatchKit SDK, all code in a Watch application runs on the phone it’s paired with, so there’s no point at which your preprocessor is going to encounter code that’s going to run on the Watch and thus not much use for a macro to tell it what to do when it does. The code in the ListerWatch target of the sample you linked to will run as an extension on the iPhone and talk to its watch UI via WatchKit.

How to use preprocessors in objective c

Hi in one of my applications I have to support that app for IOS6 & IOS7.Inorder to accomplish that first I have to know the current device version. For that I had defined one macro and I am trying to using that macro as a reference to accomplish my task. The code which I wrote is as such below.
In .h file I defined IPhoneOSVersion as 50000.
This code is in .m file
if([[[UIDevice currentDevice] systemVersion] isEqualToString:#"7.0"])
{
#undef IPhoneOSVersion
#define IPhoneOSVersion 70000
NSLog(#"_IPHONE_OS_VERSION_MIN_REQUIRED after is %d",IPhoneOSVersion);
}
else
{
#undef IPhoneOSVersion
#define IPhoneOSVersion 60000
NSLog(#"_IPHONE_OS_VERSION_MIN_REQUIRED after is %d",IPhoneOSVersion);
}
NSLog(#"_IPHONE_OS_VERSION_MIN_REQUIRED after is %d",IPhoneOSVersion);
And if i run this code in IOS7. In console the data have to print like this _IPHONE_OS_VERSION_MIN_REQUIRED after is 70000 but unfortunately I am getting _IPHONE_OS_VERSION_MIN_REQUIRED after is 60000. Even I put a break points at else condition also but that is not executing but the macro value is changing.Can anyone please let me know why the macro value changing like this.
You shouldn't be hardcoding against the OS version, Apple recommended way of supporting multiple OS versions is to check for some specific class, API, protocol or function, this allows for greater flexibility as some of that stuff is sometimes backwards compatible.
Here's a pretty decent tutorial on how to check for existence of specific resources in code http://www.raywenderlich.com/42591/supporting-multiple-ios-versions-and-devices and the docs from Apple https://developer.apple.com/library/ios/documentation/developertools/conceptual/cross_development/Using/using.html
EDIT: To answer your question on why the macro is changed, the compiler goes over both branches of the if-else, thus the last declaration of the macro is used. You can't use a macro like that and change it during runtime, macros are meant to be define before compilation.
You use the preprocessor in Objective-C in exactly the same way as in C or C++. The preprocessor doesn't care about your if/else statements. It sees a sequence of #undef, #define, #undef, #define and performs them one after the other, so in your last line, the last #define is in effect. You cannot influence these #defines with anything happening at runtime.
There are always three OS versions in play: The deployment target (that is the lowest OS version where you allow your app to run), the SDK version, and the actual version at runtime. The first two you set in Xcode; the actual version is obviously out of your control except that you know it is the same or higher than the deployment target.
__IPHONE_OS_VERSION_MIN_REQUIRED = Deployment target
__IPHONE_OS_VERSION_MAX_ALLOWED = SDK version
Try with
if([[[UIDevice currentDevice] systemVersion] floatValue] == 7.0)

Method "not available on iOS"

I heard about a function on NSCalendar that had been introduced in iOS7.
Had a look in the docs and couldn't find it. Nor in the OS X docs.
The function is - (BOOL)isDate:(NSDate *)date1 equalToDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit i.e. are these two dates on the same day/in the same week/ month, etc...
However, when I try to use it in Xcode 5. The AutoComplete shows it with a red strike through and then when I actually use it I get this error...
It's odd as the function is clearly there I'm just not able to use it.
Can anyone shed light on why this is happening?
Unfortunately it's not available for iOS, only for OS X 10.9. You can always dupe rdar://14995171 to tell Apple that you want it for iOS as well.
If you look in NSCalendar.h in the iOS 7 SDK you will see that these methods are tagged as available since __NSCALENDAR_COND_IOS_7_0 which if you look at the top of the same file is defined as
#if !defined(__NSCALENDAR_COND_IOS_4_0)
#if NS_ENABLE_CALENDAR_NEW_API
#define __NSCALENDAR_COND_IOS_4_0 4_0
#define __NSCALENDAR_COND_IOS_5_0 5_0
#define __NSCALENDAR_COND_IOS_6_0 6_0
#define __NSCALENDAR_COND_IOS_7_0 7_0
#else
#define __NSCALENDAR_COND_IOS_4_0 NA
#define __NSCALENDAR_COND_IOS_5_0 NA
#define __NSCALENDAR_COND_IOS_6_0 NA
#define __NSCALENDAR_COND_IOS_7_0 NA
#endif
#endif
This currently evaluates to NA meaning that these methods are "not available" for iOS.
Where did you hear about that method? It's possible that the method has been removed during the betas of iOS 7.
It's private API: __NSCFCalendar.h

Detect compilation on Bada OS

I would like to do something similar to #ifdef __linux__, but with the bada SDK. Is there a constant defined by default?
Also, can I detect when I am compiling for the simulator?
You can, by checking the MingW Compiler's keyword, here's an interesting link that would point you in the right spot... so in theory you could have it this way
#ifdef __MINGW32__
/* we're in the simulator target */
#else
/* we're in the native target */
#endif
I use something like :
#ifdef SHP
# define CONFIG_SUPPORT_API_Osp 1 // bada
#endif
I wish there is also a define that tell sdk version or target api too ..
Use :
#ifdef _DEBUG
// Your code
#endif

Resources