Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an integer value in Objective-C enum

Is it possible in Objective-C to see if a int value is in a particular enum? For instance, in this enum:

enum  {
  ValidationLoginFailed         = 2000,
  ValidationSessionTokenExpired = 2001,
  ValidationSessionTokenInvalid = 2002,
  ValidationEmailNotFound       = 2003  
}; 
typedef int ValidationStatusCodes;

is it possible to see if an arbitrary integer value is in the ValidationStatusCodes enum?

[ValidationStatusCodes contains:intResponseCode]

or at least

[self intIsInRangeofEnum:ValidationStatusCodes forValue:intResponseCode]
like image 499
Neil Edwards Avatar asked Dec 01 '10 21:12

Neil Edwards


People also ask

Can enum have int values?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

What is enum in Objective C?

typedef enum declaration in Objective-C A enum declares a set of ordered values - the typedef just adds a handy name to this. The 1st element is 0 etc. typedef enum { Monday=1, Tuesday, Wednesday } WORKDAYS; WORKDAYS today = Monday;//value 1.


3 Answers

There's no simpler way than just doing

(ValidationLoginFailed == intResponseCode ||
ValidationSessionTokenExpired == intResponseCode ||
ValidationSessionTokenInvalid == intResponseCode ||
ValidationEmailNotFound == intResponseCode)

In general, C is not very helpful for doing dynamic things or reflecting on types, and enums are a C feature.

like image 125
Chuck Avatar answered Oct 02 '22 10:10

Chuck


Not with an enum. An enum is not an objective-C object, so you can't send it messages as you're doing.

Maybe use an NSDictionary?

like image 28
David Gelhar Avatar answered Oct 02 '22 11:10

David Gelhar


This question is a little dated, but the standard I have seen in software design is to use a bitmask where each of these values is a discrete state with a bit-shift. In some cases, your enum values can be combinations of other values.

enum  {
  ValidationLoginFailed         = 0, //0
  ValidationSessionTokenExpired = 1 << 0, //1
  ValidationSessionTokenInvalid = 1 << 1, //2
  ValidationEmailNotFound       = 1 << 2  //4
}; 
typedef int ValidationStatusCodes;

For your use-case you would & your result with all of the items in the set:

int allStates = (ValidationLoginFailed | ValidationSessionTokenExpired | 
   ValidationSessionTokenInvalid | ValidationEmailNotFound); //7

if(val & allStates){
   //some logic here
}
like image 22
jaysqrd Avatar answered Oct 02 '22 12:10

jaysqrd