alfacan
alfacan

Reputation: 715

Objective C object by string name?

Is it possible to find the object named with specific string.

For example i can use that in php

$objectname="foo";
$foo="bar";
echo $$objectname="bar";

is this possible? objectbyname would a proper function for this.

Upvotes: 1

Views: 4820

Answers (3)

Stephen Darlington
Stephen Darlington

Reputation: 52565

It doesn't look quite as it does in PHP but, yes, it is possible to get a class from a string. You use the NSClassFromString function.

For example the following two lines are equivalent:

id a = [[NSClassFromString(@"NSString") alloc] init];
id a = [[NSString alloc] init];

Upvotes: 2

Eimantas
Eimantas

Reputation: 49344

It could be possible if you stored named objects as properties or in some sort of dictionary. Then you could do something like this:

// Put object into dictionary
[dictionaryWithObjects setValue:someNamedObject forKey:@"someNamedObject"];

// and then retrieve it
id object = [dictionaryWithObjects valueForKey:@"someNamedObject"];

And I'm not sure ObjectiveC supports that level of metaprogramming.

Upvotes: 4

Gordon Christie
Gordon Christie

Reputation: 609

You can use NSClassFromString() to get a class, but for specific instances of an object I don't think this is possible.

Upvotes: 0

Related Questions