开发者

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

开发者 https://www.devze.com 2023-04-06 22:02 出处:网络
How can I get an object based from a string in Objective C? For example int carNumber=5; [@\"car%i\",carNumber].speed=10;

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 jus开发者_如何学编程t made up objects, but how could I get an object based on what is in a variable.


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

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


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;


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.


Why not just store the car objects in an NSArray?

0

精彩评论

暂无评论...
验证码 换一张
取 消