Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store enum val in NSDictionary

Tags:

objective-c

I have a bunch of JSON objects coming back from a server and I'm trying to normalize them a little in my objective C.

I have this enum:

//VP_STATUS
typedef enum {
    VP_STATUS_NA,
    VP_STATUS_STEXP,
    ...
    VP_STATUS_COUNT
} VP_STATUS;

I have a function that maps the string in a JSON object (which is an NSMutableDictionary) to this enum and then I try and set a key "status" on the NSMUtableDictionary like so:

VP_STATUS status = [myStringToEnumMappingFunction:[p objectForKey:@"status_label"]];
[p setValue:status forKey:@"status"];

However, on the setValue:forKey line I get this error:

"Implicit conversion of VP_STATUS to id is disallowed with ARC"

Do I first have to convert status to something else? If so, then that kind of defeats the purpose of using messages that are defined as VP_STATUS's, doesn't it?

I'm fairly new to objective-c so I could be doing this entirely wrong for all I know and am open to suggestions.

like image 678
Adam Avatar asked Dec 09 '22 15:12

Adam


1 Answers

Enums are like aliases for numbers. The Objective-C collection classes can only store object references.

The error you are getting is saying that a value cannot be converted to an id (id is another way of writing NSObject *), an object pointer.

If you want to store an value in a collection, you need to wrap it in somthing like an NSNumber. If you are using LLVM you can do this for example with:

[p setValue:@(status) forKey:@"status"];

And to compare it again you can turn it back into a number with:

VP_STATUS status = [[p valueForKey:@"status"] integerValue];
like image 178
Abizern Avatar answered Mar 06 '23 16:03

Abizern