Objective-C - 定义一个可以点调用的枚举,如 ENUMTYPE.ENUMVAL
我读过很多关于 Objective-C 中枚举类型的内容,并且我发现有很多方法来定义它们。但我没有看到正确的方法(如果有的话)来定义可以用 CARS.ROLLSROYCE 调用的枚举,并且不能仅在代码中与 ROLLSROYCE 一起使用。
因此,我可以在 CARS 枚举和 BEAUTIFULCARS 枚举中定义 ROLLSROYCE。
你知道定义这样一个枚举的方法吗?
I've read many things about enum types in objective-c, and I see there is many ways to define them. But I don't see the right way (if there is one) to define an enum that can be called with CARS.ROLLSROYCE and that cannot be used only with ROLLSROYCE in the code.
So I can define ROLLSROYCE in the CARS enum and also in the BEAUTIFULCARS enum.
Do you know the way to define such an enum ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试在 Objective-C 中为枚举实现名称空间。您所要求的是 Objective-C 中的大量苦劳。为此,您可能最好使用 C++,因为它很简单,而且据我所知,任何 iOS 或 Cocoa 应用程序都完全支持它。您必须将
#import
C++ 代码的文件重命名为.mm
文件,而不是.m
文件,并且 C++ 编译器可以比 Objective-C 更棘手。按照这条路线,您将创建一个头文件,例如Enums.h
。在您的
.mm
源文件中,如果您想避免使用 C++ 来实现此解决方案,则需要更多的体力劳动、簿记工作和出错的机会。为此,您需要一个标头和一个源文件。
您的
.m
源代码几乎相同:Objective-C 并不像大多数其他 OO 语言那样管理范围。接口定义接口支持的对象的属性和消息,但不支持公共或私有等保护级别。当您在 @interface 中定义枚举时,该枚举最终位于全局范围内。
You are trying to implement namespaces for your Enums in Objective-C. What you're asking for is a lot of elbow grease in Objective-C. You are probably best-off using C++ for this, since it is easy and afaik fully supported in any iOS or Cocoa application. You'll have to rename the files that
#import
your C++ code to.mm
files instead of.m
files, and the C++ compiler can be trickier than the Objective-C one. Going this route you'll create a header file likeEnums.h
.And in your
.mm
sourcefileIf you want to avoid using C++ for this solution, there's a lot more elbow grease, bookkeeping, and opportunity for error. You'll need a header and a source file for this.
Your
.m
source is almost the same:Objective-C does not manage scope in the same way that most other OO languages do. Interfaces define the properties and messages that an object that interface supports, but don't support protection levels like public or private. When you define an enum in an
@interface
, that enum ends up in global scope.对于我的例子,我不想使用 C++ 命名空间或为这样一个简单的例子编写冗余的 Objective-C 类,所以我回到了 C。
然后在 Enum.m 中定义值
最后,在你的“main”中" 代码
将产生以下输出:
For my case, I didn't want to use C++ namespaces or write redundant Objective-C classes for such a simple case, so I fallen back to the C.
And then in Enum.m, define values
And finally, in your "main" code
Which will produce this output: