Reputation: 36013
I have several objects that I want to use, like obj11, obj21, obj33, etc.
The choice of the correct object to use depends on some parameters defined by the user, like for example: size to use and kind of object.
so, the first number on the object name will represent the size and the second letter the kind. If the user choose the object size 2 and the object kind 1, the object to load will be "obj21".
Is there a way to reference an object based on its name as a NSString?
something like
NSString *name = [NSString stringWithFormat:@"obj%d%d", size, kind];
["use object name" doSomething];
I need something like NSSelectorFromString, but in this case, it runs a method based on its name. What I need is something like "NSObjectFromString", that references an object based on its name as string.
How do I do that? Thanks.
Upvotes: 0
Views: 184
Reputation: 5766
Since this is not possible, it would be a better idea to store your objects in an NSDictionary (or its mutable counterpart) and use the string you build as key for that object.
Here's an weird example:
NSMutableDictionary *objectDict = [[NSMutableDictionary alloc] init];
... init your objects somehow ...
// build your keys somehow and add the object to the dict
int size = 1;
int kind = 2;
NSString *name = [NSString stringWithFormat:@"obj%d%d", size, kind];
[objectDict addObject:obj12 forKey:name];
... Do some stuff ...
// access your object and call a method
id obj = [objectDict objectForKey:name];
[obj doSomething];
Upvotes: 3
Reputation: 10407
You can make a factory method and use NSSelectorFromString
to call it dynamically.
More details here:
EDIT:
My answer to what I think is the same question:
id object = [[NSClassFromString(@"NameofClass") alloc] init];
Create objective-c class instance by name?
Upvotes: 0