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 int开发者_如何学编程s 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!
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.
make use of Objective-C's dynamic typing with id
- (id) getValueforKey:(NSString *)key {
some magic here....
return value;
}
精彩评论