I'm trying to implement a specialized typed
logger that takes a dictionary as input and creates string of values out of it.
One sample such dictionary might be:
CGSize size = {300, 200} ;
CGAffineTransform t = ::CGAffineTransformIdentity ;
[self logit: @{
@"columns": @{
@"value": @3
, @"type": @"NSNumber"
}
, @"size": @{
@"value": [NSValue valueWithCGSize(size)]
, @"type": @"CGSize"
}
, @"transform": @{
@"value": [NSValue valueWithCGAffineTransform(t)]
, @"type": @"CGAffineTransform"
}
}] ;
The issue is: how do I retrieve those values in a generic way?
I could obviously write
for (NSString * key in dict) {
NSDictionary * params = dict[key] ;
if ([params[@"type"] isEqualToString: @"CGRect"]) {
CGRect r = [params[@"value"] CGRectValue] ;
NSString * s = ::NSStringFromCGRect(r) ;
::NSLog(s) ;
} else if ([params[@"type"] isEqualToString: @"NSNumber"]) {
::NSLog(@"%.3f", [params[@"value"] floatValue]) ;
} else if ([params[@"type"] isEqualToString: @"CGAffineTransform"]) {
CGAffineTransform t = [params[@"value"] CGAffineTransformValue]
NSString * s = ::NSStringFromCGAffineTransform(t) ;
::NSLog(s) ;
}
...
}
But I'd rather write a more "generic" solution. Something along the lines:
SEL valueSelector = ::NSSelectorFromString([NSString stringWithFormat:@"%@Value", params[@"type"]) ;
NSString * rawCFunctionName = [NSString stringWithFormat:@"NSStringFrom%@", params[@"type"]] ;
So now I have a selector and the name of a C function.
How do I go from a string to a C function that I can actually call?
using the selector above is unclear as its return type can vary from
id
e.g.: in the case ofNSNumber *
to "plain C object" e.g. in the case ofCGRect
,CGSize
etc ...
Any suggestion?