views:

366

answers:

4

Does anyone know how to (or if) you can convert a string to an enumerated type in the objective-c/cocoa/iphone environment?

For example:

If I have an XML document with the element:

<dog breed="GermanShepard">

I would like to be able to read the "breed" attribute into an NSString and then convert it into a type "Dogs" as defined here:

typedef enum 
{   
Poodle,
GoldenRetriever,
GermanShepard,
Collie
} Dogs;

Dogs myDog = <string that came from the breed attr in the XML>

Any assistance is appreciated...

Also, I just want to clarify that I AM able to retrieve the attr value from the XML (this is pretty straightforward). However, my issue is that once I have an NSString, I am unable to convert it to an enumerated type (ie. the Dog type in the example). I only included the XML example above as a means of illustrating why I would want to do such a thing.

A: 

If you use NSXMLParser, this will be contained within the xml attributes passed to theparser:didStartElement:namespaceURI:qualifiedName:attributes: delegate method. when it is called for the dog element.

The attributes are held in a NSArray keyed with the attribute name. In your case "breed". So, you access the string containing the dog's name using:

NSString* breedName = [attributesDictionary objectForKey:@"breed"];

Then you have a string you can compare (using NSString's comparisons) to your dog names.

You could get slightly neater code by making your own NSDisctionary of NSNumbers containing your enum values keyed by the textual dognames - note that this will be slightly slower and will not allow you as much flexibility in your comparisons.

Roger Nolan
+2  A: 

I'm fairly sure that the enum values are replaced with integers at compile time, so you'll either have to test individually for matches with strings, or have an array of your enum values that you call indexOfObject: on.

cobbal
+1  A: 

A similar question was asked here, and I think that many of the generic Cocoa-based answers given there might be useful in your case.

Brad Larson
+2  A: 

There's no way to do this out of the box. You'll need to make a table that allows you to associate the strings with the appropriate integer values at runtime.

Chuck
I was afraid of that. Oh well... thanks chuck.