Take the 2-minute tour ×

I'll use an example from JavaScript to help clarify my question. Let's assume I have the following object:

sports = {
   soccer: {...},
   basketball: {...},
   baseball: {...}

If at some point in my script I have a variable, sportString, that simply holds a string, I can dynamically call one of the sports objects in the following way:


This frees me from having to use a bunch of nested if statements, testing the value of the string such as:

if(sportString === 'soccer'){
}else if(sportString === 'basketball){....

So, my question is how can I accomplish something similar to sports[sportString] in Objective-C, if sportString is an NSString object?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

Use an NSDictionary as your sports object. Then you can do lookups like this:

[sports objectForKey: sportsString];
share|improve this answer
Thanks. Giving this one the answer since it's the first. –  maxedison Jul 9 '11 at 11:47

The people saying you should use NSDictionary for general key/value storage are 100 % right. However, I think it’s useful to know that you can call a message specified by a string:

SEL selector = NSSelectorFromString(@"foo"); // Or @selector(foo) if you know it at compile time
id value = [object performSelector:selector];

You can also use selectors with up to two arguments, as long as they take objects:

SEL selector2 = NSSelectorFromString(@"setFoo:");
[object performSelector:selector2 withObject:value];

It’s possible to invoke arbitrary methods using IMPs or casting objc_msgSend(), but now I’m getting way beyond the scope of your actual question. :-)

share|improve this answer
Thanks for posting this. Definitely useful to know about NSSelectorFromString and performSelector. I really appreciate it! –  maxedison Jul 9 '11 at 16:23

Your JavaScript object sports would typically be an NSDictionary or NSMutableDictionary. Example:

NSMutableDictionary *sports = [NSMutableDictionary dictionary];
[sports setObject:@"Foo" forKey:@"soccer"];
[sports setObject:@"Bar" forKey:@"basketball"];

NSString *sportString = @"soccer";
NSString *sportValue = [sports objectForKey:sportString];
NSLog(@"%@", sportValue); //logs "Foo"
share|improve this answer

Your Answer


