jadengeller
jadengeller

Reputation: 1327

How do you get an object from a string in Objective C?

How can I get an object based from a string in Objective C?

For example

int carNumber=5;
[@"car%i",carNumber].speed=10;
//should be same as typing car5.speed=10;

Oh course, those are just made up objects, but how could I get an object based on what is in a variable.

Upvotes: 2

Views: 169

Answers (4)

zaph
zaph

Reputation: 112857

int carNumber = 5;
NSString *className = [NSString stringWithFormat:@"car%d", carNumber];
Class carClass = [[NSBundle mainBundle] classNamed:className];
if (carClass) {
    id car = [[carClass alloc] init];
    [car setValue:[NSNumber numberWithInt:10] forKey:@"speed"];
}

But there are issues such as saving try car class instance for later access, perhaps adding it to an NSMutableArray.

Upvotes: 0

dtuckernet
dtuckernet

Reputation: 7895

If you follow Key-Value Coding then this is as easy as:

NSString *myValue = [NSString stringWithFormat:@"car%@", carNumber];
id myValue = [myClass valueForKey:myValue];

Upvotes: 4

edc1591
edc1591

Reputation: 10182

Why not just store the car objects in an NSArray?

Upvotes: -1

Luke
Luke

Reputation: 7210

You cannot. When your code is compiled, the names of variables will no longer be what you've specified. car5 is not and has never been a string.

The better strategy would be to have an array of car objects and then specify the index. In C style (where carType is the type of each car):

carType carArray[5];

//! (Initialize your cars)

int carNumber= 5;
carArray[carNumber].speed= 10;

In Objective-C, if your cars are objects:

NSMutableArray* carArray= [[NSMutableArray alloc] init];

//! (Initialize your cars and add them to the array)

int carNumber= 5;
carType car= [carArray objectAtIndex:carNumber];
car.speed= 10;

Upvotes: 0

Related Questions