1

I have an objective C method which passes in a string and an integer as its arguments. Inside of this method, I want to use a selector - the name of which is based upon the integer value I am passing in. For example, if the integer argument is 5, I want the selector to be named "buildXArrayIndex5" or if the integer argument is 3, I want the selector to be named "buildXarrayIndex3." I am really at a loss for how to do this or if it is possible/reasonable. I am new to objective C, so I wrote out what I want to happen, but it is not working/valid code. But here it is:

- (void) startBuildingXArray:(int)senderID:(NSString *)moveTrackerObject {

NSString *methodNamePrefix = @"buildXArrayIndex";

NSString *realMethodName = [[NSString alloc]initWithFormat:@"%@%d",methodNamePrefix,   
senderID];

SEL realSelector = NSSelectorFromString(realMethodName);

[self realSelector: moveTrackerObject];

}

In the interface, I declared SEL realSelector; but I am getting an error without running this that says"no visible @interface declares the selector realSelector." But I'm sure that this is not the only problem with this code. Can anyone tell me how to create the proper code for this or highlight a better approach?

jac300
  • 5,182
  • 14
  • 54
  • 89
  • Also see [this question.](http://stackoverflow.com/q/112643/868193) – Beltalowda Oct 22 '12 at 16:22
  • 2
    What are you trying to achieve? In general while you are new to programming there is no need to make such extravaganza moves like this as everything can be done with proper OO application design – pro_metedor Oct 22 '12 at 16:28
  • possible duplicate of [How to Make a Dynamically Named Method Parameter?](http://stackoverflow.com/questions/12992034/how-to-make-a-dynamically-named-method-parameter) – jscs Oct 22 '12 at 18:59

1 Answers1

3

You need to call your selector using -performSelector: method, e.g.:

[self performSelector:realSelector];

Also if methods you want to call accept parameter you need to add a colon to selector name:

NSString *realMethodName = [[NSString alloc]initWithFormat:@"%@%d:",methodNamePrefix, senderID];

and call it:

[self performSelector:realSelector withObject:moveTrackerObject];
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Thank you - one more question though - now I am getting an error that says "performSelector may cause a leak because its selector is unknown." I must be missing something... – jac300 Oct 22 '12 at 16:50
  • @user1697845, check this question http://stackoverflow.com/questions/11895287/performselector-arc-warning . it seems you'll have to suppress warning using pragmas – Vladimir Oct 22 '12 at 17:06