Enumerations in Objective-C VS C

SA, I know that Objective-C is a strict superset of C ..

But when I tried a very simple enumeration example that I used to use in C, it did not work in the C object,

Here is the code:

#import <Foundation/Foundation.h> int main(void) { typedef enum { SUN, MON, TUES }DAYS; DAYS d = MON; NSLog(@"%@", d); return 0; } 

 #include <stdio.h> int main(void) { typedef enum { SUN, MON, TUES }DAYS; DAYS d = MON; printf("%d\n", d); return 0; } 

In C it works fine, but in Objective-C (I use GNUstep in WIN) it crashes at runtime (without compile-time errors)

Can someone tell me why?

+4
source share
5 answers

%@ is the specifier of the object, and enumerations are int (signed or unsigned). To print an enumeration in Objective-C, you need to use %d in NSLog .

 NSLog(@"%d", d); 

Your original example failed because it expected d be an object, so it will try to send a description message to the object located at memory address 1 (value MON ).

+17
source

try it

 int main(void) { typedef enum { SUN, MON, TUES }DAYS; DAYS d = MON; NSLog(@"%d", d); //here is your mistake happened, because enum return values are integers. return 0; } 

Hope for this help

+3
source

It crashes due to the NSLog(@"%@") instruction NSLog(@"%@") . The %@ format NSObject* expects an instance of NSObject* (or a subclass) while you pass an enum element (i.e. int ).

Try NSLog("%d\n", d);

+2
source

Just use

 NSLog(@"%d", d); 

instead

 NSLog(@"%@", d); 

Remember that in Objective-C, not everything automatically becomes an object. Primitive types in C are still primitive types. Therefore, in the NSLog formatting string, you still need to use the same qualifier that you always used.

+2
source

And with boxed expressions, you can continue to use% @ in format specifiers:

 NSLog(@"%@", @(d)); 

This is not entirely optimal, but it really is not a problem during debugging. If you are dumping numbers formatted in milliseconds, go to the desired format.

0
source

All Articles