Adding a integer after variable name to access

核能气质少年 提交于 2019-12-12 03:46:27

问题


I am trying to run an action, but i want to decide which. for example i have

[bullet runAction:bullet1];

I want to be able to manipulate the variable its accessing something like

[bullet runAction:bullet%d, i];

回答1:


use an array of actions, and use the index to access them

NSArray bulletActions = @[bullet1, bubble2];
[bullet runAction:bulletActions[0]];

I think it will serve your needs




回答2:


You need to use selector

 SEL selector=NSSelectorFromString([NSString stringWithFormat:@"bullet%d", i]);
[self performSelector:selector];

From this you can call a method named bullet1, buttet2 etc, if i is provided as 1, 2 etc

-(void)bullet1{
    NSLog@"bullet 1 called";
}


-(void)bullet2{
    NSLog@"bullet 2 called";
}

-(void)bullet<your integer value>{
    NSLog@"bullet <your integer value> called";
}



回答3:


EDIT: Sorry, after looking at my answer I saw some flaws and wrote this as a better way to accomplish this.

The best possible outcome for this is to create an array that holds all of your actions. i.e.

NSArray actionArray = [[NSArray alloc] initWithItems:bullet1, bullet1, bullet3, nil];

And then you can run create a method to run the action:

- (void)bulletAction:(int)numberToRun {

     [bullet runAction:[actionArray objectAtIndex:numberToRun]];

}

This can be called by using the code:

[self bulletAction:0];

Where 0 is whatever number you want to run.




回答4:


you cant do what you are trying to do in the question, instead pass it an array of bullet objects and also pass it the value for which element you want to access of that array.



来源:https://stackoverflow.com/questions/15292997/adding-a-integer-after-variable-name-to-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!