views:

28

answers:

2

Hi everyone

I have a configuration class in my objective-c app which reads a PLIST file with configuration data. I would then like to be able to read the value for any key with a single function, something like this:

- () getValueforKey:(NSString *)key {
     some magic here....
     return value;
}

The issue: Some of the values in the config file are Strings, others are ints or even Dictionaries. As you can see I left the return-type blank in this example as I do not know what to write there. Is there any way that a function can return different types of data, and if so, how do I declare this?

Thanks a lot!

+2  A: 

The safest is to provide a distinct method for each type you support:

- (NSString *)stringForKey:(NSString *)key;
- (int)intForKey:(NSString *)key;
- (float)floatForKey:(NSString *)key;
- (NSDictionary *)dictionaryForKey:(NSString *)key;
...

You could supply a generic one in case the caller wants to work generically:

- (id)objectForKey:(NSString *)key;

In this case you would return NSString *, NSNumber *, NSDictionary *, etc.

Marcelo Cantos
I was thinking about the first one too, yet I prefer a single function. Thanks a lot!
Robin
If you find yourself writing lots of `isKindOfClass:` based conditional code, it generally indicates that your code is not following patterns consistent with the frameworks.
bbum
A: 

make use of Objective-C's dynamic typing with id

- (id) getValueforKey:(NSString *)key {
     some magic here....
     return value;
}
Davi
Won't work for `int`, `float` and other non-object data types.
Douwe Maan