9

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.

James Webster
  • 31,873
  • 11
  • 70
  • 114

2 Answers2

24

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

Felix
  • 35,354
  • 13
  • 96
  • 143
  • 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. – Slipp D. Thompson Oct 23 '13 at 01:53
9

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

Community
  • 1
  • 1
James Webster
  • 31,873
  • 11
  • 70
  • 114
  • that question is referring to subscripting, which is only available in iOS 6 because it is more than syntactic sugar. number/bool/collection literals should be available in previous versions – wattson12 Jul 27 '12 at 11:01
  • Hmm - interesting - I just converted my ios5.0 project to the new literals, and all but subscripting is working just fine. – David H Jul 27 '12 at 11:31
  • Well, there is a way to get it all now - see http://stackoverflow.com/a/11694878/96716. I included your code above with attribution and link. – David H Jul 27 '12 at 20:01
  • I like this answer more— it's a nice “polyfill” approach, rather than a wait-it-out one. – Slipp D. Thompson Oct 23 '13 at 01:51
  • Also, like @phix23's answer, 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. – Slipp D. Thompson Oct 23 '13 at 01:53