Objective-C 中的枚举 VS C
萨, 我所知道的是,Objective-C 是 C 的严格超集。
但是当我尝试了一个以前在 C 中使用的非常简单的枚举示例时,它在 Objective C 中不起作用,
这是代码:
#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;
}
在 C 中,它工作得很好,但是在 Objective-C 中(我在 WIN 上使用 GNUstep),它在执行时崩溃(没有编译时错误)
有人能告诉我为什么吗?
SA,
What I know is that Objective-C is a strict superset of C..
But when I've tried a very simple enum example that I used to use in C, it didn't work in objective C,
Here's 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 perfectly, but in objective-c (I am using GNUstep on WIN) it crashes when executing (no compile-time errors)
Can anyone tell me why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
%@
是一个对象说明符,枚举是一个 int(有符号或无符号)。要在 Objective-C 中打印枚举,您需要在NSLog
中使用%d
。您原来的示例崩溃了,因为它期望
d
是一个对象,因此它会尝试将description
消息发送到驻留在内存地址1
的对象>(MON
的值)。%@
is an object specifier and enums are an int (signed or unsigned). To print an enum in Objective-C you need to use%d
in yourNSLog
.Your original example was crashing because it expected
d
to be an object so it would try and send thedescription
message to an object residing at memory address1
(the value ofMON
).试试这个
希望有帮助
Try this
Hope this help
只需使用
而不是
记住,在 Objective-C 中,并不是所有东西都会自动成为对象。 C 中的原始类型仍然只是原始类型。因此,在
NSLog
的格式化字符串中,您仍然需要使用始终使用的相同说明符。Just use
instead of
Remember, in Objective-C, not everything automatically becomes an object. Primitive types in C are still just primitive types. Therefore, in
NSLog
's formatting string, you still need to use the same specifier you always used.它因
NSLog(@"%@")
语句而崩溃。%@
格式说明符需要一个NSObject*
(或子类)的实例,而您传递enum
项(ie.< /em>int
) 。尝试
NSLog("%d\n", d);
It crashes because of the
NSLog(@"%@")
statement. The%@
format specifier expects an instance ofNSObject*
(or a subclass), while you passenum
item (ie.int
) .Try
NSLog("%d\n", d);
对于盒装表达式,您可以继续在格式说明符中使用 %@:
这并不完全是最佳选择,但在调试时这确实不是问题。如果您要转储数百万个字符串格式的数字,请使用正确的数字格式。
And with boxed expressions, you can keep on using %@ in your format specifiers:
This is not exactly optimum, but it's really not a problem while you're debugging. If you're dumping string-formatted numbers by the millions, go with a proper number format.