Robin
Robin

Reputation: 8357

Variable return type in objective-c function (with Cocoa)

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!

Upvotes: 2

Views: 3516

Answers (2)

Davi
Davi

Reputation: 11

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

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

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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.

Upvotes: 5

Related Questions