问题
In Objective C, when you define an enum, all of the enum values are visible everywhere and clog the global namespace.
I would like to make it Java-style and enforce that enums are only accessible thru the enum type name, e.g. with
typedef enum
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, NUM_OF
} Day;
I want to make sure that
simply calling MONDAY produces compilation error or at least warning, and the only way to access the enum value were something like Day.MONDAY or Day::MONDAY or [Day MONDAY] or...
In Java I either use Enums or Interfaces, but is this doable in Objective-C?
If not, then I'd have to name all enums like this: DAY_MONDAY, DAY_TUESDAY... to make them easier to seach in auto-completion pop-up.
回答1:
It's just a workaround, but you can create a custom interface with a number of class methods (so that there's no need to create an instance), where each method represent a constant.
This way constants will be accessible only as you asked (ie. Day.MONDAY or [Day MONDAY]).
来源:https://stackoverflow.com/questions/7388997/how-to-limit-visibility-of-enum-values-in-objective-c