Consider an object chain like:
foo.bar.baz.bing
In this particular instance, I am given foo and I wish to evaluate the method bing. In code I would do the following:
[[[foo bar] baz] bing];
Or, if bing were a property, I could evaluate it thusly:
id result = foo.bar.baz.bing;
Now consider the situation where I am given foo and then bar.baz.bing in the form of an NSString object. I came up with the following method to evaluate down to bing, but I am wondering if there is a simpler way to do this.
- (id)evaluator:(id)parentObject withChain:(NSString *)objectChain
{
id currentObject = parentObject;
for (NSString *component in [objectChain componentsSeparatedByString:@"."])
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
currentObject = [currentObject performSelector:NSSelectorFromString(component)];
#pragma clang diagnostic pop
}
return currentObject;
}
Note: The above code example was contrived to demonstrate the point. I am aware of the dangers of calling init, alloc, copy, mutableCopy, or new using a method like this. The actual use in code is very carefully managed to avoid any situations where ARC would require a release.
Use Key-Value Coding.