How do I append a string/number to a string ?

2019-03-04 23:08发布

问题:

I have a function

 -(void) generateLevelFromPlist:(int)currentLevel{
    NSString *mainPath = [[NSBundle mainBundle] bundlePath];
    itemPositionPlistLocation = [mainPath stringByAppendingPathComponent:@"levelconfig.plist"];
    NSDictionary * itemPositions = [[NSDictionary alloc] initWithContentsOfFile:itemPositionPlistLocation];
    NSNumber *xVal = [[[[itemPositions objectForKey:@"level + STRING/NUMBER"]objectForKey:@"hexposition"]objectForKey:@"hexagon1"]objectForKey:@"xVal"];
    int generatedXVal = [xVal integerValue];
    NSLog(@"%d", generatedXVal);
    NSLog(@"%@", itemPositionPlistLocation);



    }

where I want to add the variable currentLevel to the string "level" as in objectForKey:@"level + STRING/NUMBER"

How do I do that ?

回答1:

There are lots of ways to do this. The easiest in this case is:

myString = [NSString stringWithFormat:@"level + %d", currentLevel]

Or

myString = [NSString stringWithFormat:@"%@ %d", initialString, currentLevel]

You might also consider using valueForKeyPath: rather than objectForKey over and over. ([x valueForKeyPath:@"a.b.c"] is similar to [[[x objectForKey:@"a"] objectForKey:@"b"] objectForKey:@"c"])