Apr. 18th, 2024
2024年 3月 10日

Post: Difference between enum and NS_ENUM in Objective-C

Difference between enum and NS_ENUM in Objective-C

Published 12:11 Nov 06, 2014.

Created by @ezra. Categorized in #Programming, and tagged as #iOS.

Source format: Markdown

Table of Content

First, NS_ENUM uses a new feature of the C language where you can specify the underlying type for an enum. In this case, the underlying type for the enum is NSInteger (in plain C it would be whatever the compiler decides, char, short, or even a 24 bit integer if the compiler feels like it).

Second, the compiler specifically recognises the NS_ENUM macro, so it knows that you have an enum with values that shouldn't be combined like flags, the debugger knows what's going on, and the enum can be translated to Swift automatically.

NS_ENUM allows you to define a type. This means that the compiler can check if you're assigning the enum to a different variable like so:

//OK in both cases
NSInteger integer = SizeWidth;
//OK only with typedef
BOOL value = SizeHeight;

NS_ENUM also provides checks in switch statements that you've covered all possible values:

//Will generate warning if using `NS_ENUM`
switch(sizeVariable) {
    case SizeWidth:
        //Do something
Pinned Message
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF