Enumeration String Comparison

I need to compare the enumeration as a whole with one line, so the entire contents of the enumeration is checked.

It takes something like:

NSString *colString = [[NSString aloc] initWithString:@"threeSilver"]; typedef enum { oneGreen, twoBlue, threeSilver }numbersAndColours; if (colString == numbersAndColours) { //Do cool stuff } 

But obviously I can’t do this, maybe the structure ... sorry, I'm new to C, please help?

By the way: I know that NSString is not C, but decided that this question is more C than Obj-C.

thanks

+4
source share
3 answers

In C, you will need to write a function for this. Essentially it will be a switch .

 char* colour_of(enum numbersAndColours c) { switch( c ) { case oneGreen: return "oneGreen"; break; case twoBlue: return "twoBlue"; break; /* ... */ default: return "donno"; } } 

You can use the function like this:

 { char* nac; nac = colour_of(numbersAndColours); if( strncmp(colString, nac, colStringLen) == 0 ) /* ... */ } 

If colString does not match any of the enumeration elements, it will not match numbersAndColours . There is no need to compare it with all the elements.

+3
source

C, ObjC and C ++ do not support this directly, you need to create an explicit mapping.

An example of using plain C:

 typedef struct { numbersAndColours num; const char* const str; } entry; #define ENTRY(x) { x, #x } numberAndColours toNum(const char* const s) { static entry map[] = { ENTRY(oneGreen), ENTRY(twoBlue), ENTRY(threeSilver) }; static const unsigned size = sizeof(map) / sizeof(map[0]); for(unsigned i=0; i<size; ++i) { if(strcmp(map[i].str, s) == 0) return map[i].num; } return -1; // or some other value thats not in the enumeration } #undef ENTRY // usage: assert(toNum("oneGreen") == oneGreen); assert(toNum("fooBar") == -1); 

The basic Objective-C approach:

 #define ENTRY(x) [NSNumber numberWithInt:x], @#x NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: ENTRY(oneGreen), ENTRY(twoBlue), ENTRY(threeSilver), nil]; #undef ENTRY if([dict objectForKey:@"oneGreen"]) { // ... do stuff } 
+2
source

I'm not sure I understand what you are trying to achieve, but you might like to watch NSSet seems like you want your program to do cool things if the colString value is a specific value.

 NSSet *numbersAndColors = [NSSet setWithObjects:@"oneGreen", @"twoBlue", @"threeSilver", nil]; NSString *colString = [[NSString alloc] initWithString:@"threeSilver"]; if ([numbersAndColors containsObject:colString]) { // do cool stuff } 

And NSSet faster than NSArray when you just want to know if a particular object exists, but one important aspect in NSSet is that it does not support the order of objects. It is usually used when you do not need order and you just want to check if an object exists in the set.

+1
source

All Articles