views:

99

answers:

2

Is there a Cocoa class has similar functionality to enumerated values from C? I know that I can just use enums in Cocoa, but what if I want to put an enum in an NSArray (which only accepts objects)?

+6  A: 

An enum is just an integer type - you can wrap it in NSNumber to put it in an NSArray.

Carl Norum
+1 i do this quite frequently
Dave DeLong
+4  A: 

In Cocoa, global constants are usually used in place of enums in places where the values will logically be included in a collection. For example:

NSString * const HandTool = @"HandTool__InternalValue";
NSString * const BrushTool = @"BrushTool__InternalValue";
NSString * const EraserTool = @"EraserTool__InternalValue";

For example, all the NSAttributedString keys are enum-like, but are represented in this way.

Chuck
Reasons to use enumerations include the ability to define the values as bit-masks, which you can OR together and cheaply test specific bits within, and the ability to use them as cases in a `switch` statement. Reasons to use objects include the ability to use them as keys in a dictionary (as demonstrated by the NSAttributedString attribute names) or as objects in a collection or archive without having to box them up.
Peter Hosey