Search code examples
iosobjective-ccastingplistinfo.plist

Correctly casting info.plist entries to NS* types


I want to write a helper class to get values from my info.plist and have them be cast to their correct type. So, if I try to access a property that's actually a number as a date, I should get back nil or an error.

I'm having trouble coming up with a nice way to check the type. I've tried to read [val class]. In the example below, it comes back as __NSTaggedDate for date values, which seems like an implementation detail I don't want to rely on.

    - (NSDate *)dateConfig:(NSString *)name
    {
        _configs = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"myConfigDictionary"];
        id val = [_configs objectForKey:name];

        // TODO how do I tell?
        if([val class] != ???)
        {
            return nil;
        }

        return val;
    }

I want to do this reliably for all other plist types as well. What's an elegant way to get this done?


Solution

  • You are looking for the message isKindOfClass:

    if([val isKindOfClass:[NSNumber class]])
    {
        return (NSNumber *)val;
    }
    else
    {
        return nil;
    }
    

    Be aware that there is also isMemberOfClass: but you rarely would want this. Many foundation objects are really Core Foundation based (i.e. NSString is NSCFString most of the time).