Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert id into enum using objective-c

I am trying to implement a simple method, however I am still quite a newbie on objective-c.

I have this simple method which is trying to convert from an id to a specific value in enum, if matched.

This is the enum

typedef enum {
   DXTypeUnknown = 0,
   DXDatasource = 1,
   DXGroup = 2
} DXPropertyType;

And this is the relevant method:

-(DXPropertyType)typeFromObject:(id)_type {
    int _t = [_type intValue];

    switch (_t) {
        case DXDatasource:
            return [NSNumber numberWithInt:DXDatasource];
        case DXGroup:
            return [NSNumber numberWithInt:DXGroup];


        default:
            return [NSNumber numberWithInt:DXTypeUnknown];
    } 
}

The very first check I would to implement is if the id can be converted to an int, then see if it falls in the two relevant categories group or datasource, or return a default value if not. Could you tell me if the switch/case I implemented is a proper solution or not ? I would like also this method not to causing crash of an application, so what could be advisable to check, keeping in mind that in any case the default value is to be returned.

thanks

[EDIT] I forgot to say that this value is going to be stored in a field of a NSManagedObject, which by CoreData restriction can be an NSNumber, so probably there's a better solution instead of an enum.

like image 455
Leonardo Avatar asked Oct 10 '22 13:10

Leonardo


1 Answers

It might be a good idea to include this code to check if the id can be used:

if (![_type respondsToSelector:@selector(intValue)])
    return nil;

However, if you'll always pass a NSNumber go ahead and declare the method as:

- (DXPropertyType)typeFromObject:(NSNumber)_type;

In your code, you're returning a NSNumber. I don't think that's what you really want, as you'd be doing nothing with the NSNumber passed. Return the enum item:

-(DXPropertyType)typeFromObject:(id)_type {

    if (![_type respondsToSelector:@selector(intValue)])
        return nil;

    int _t = [_type intValue];

    switch (_t) {
        case DXDatasource:
            return DXDatasource;
        case DXGroup:
            return DXGroup;


        default:
            return DXTypeUnknown;
    } 
}

And then this can be simplified to:

- (DXPropertyType)typeFromObject:(id)_type {

    if ([_type respondsToSelector:@selector(intValue)]) {

        int t = [_type intValue];
        DXPropertyType property_t;

        if (t >= 1 && t <= 2)
            property_t = t;
        else
            property_t = DXTypeUnknown;

        return property_t;
    }
    return nil;
}
like image 63
sidyll Avatar answered Oct 14 '22 02:10

sidyll