Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you store multiple methods in one selector?

i have a puzzle like program where you put blocks together in the right order to try and complete the puzzle. and when you are done you can hit the play button and then the program will make a little man walk across your blocks in the places where your blocks are. So if you placed one block up, one block right, one block down, and then hit play the program would call then call the methods move up, move right, move down.

When my program runs and tries to figure out what methods to call and in what order, i need to store these methods in an order as the program finds them, basically, i can't have the program immediately call the methods right when it figures out what methods to call or else the guy moving on the blocks would move lightning fast, i want to store the methods in some sort of method array (which i thought would be like a selector of some sort) so that i can call each method in a certain time interval after my program has figured out everything its going to do.

my normal program right now looks something like this

if(random requirements)
[self moveUp]

else if(random requirements)
[self moveDown]

else if (random requirements)
[self moveRight]

else if(random requirements)
[self moveLeft]

well, i would rather this look something like this

if(random requirements)
SEL selector addMethod:[self moveUp]

else if(random requirements)
SEL selector addMethod:[self moveDown]

else if (random requirements)
SEL selector addMethod:[self moveRight]

else if(random requirements)
SEL selector addMethod:[self moveLeft]

obviously this isn't real syntax but can you kind of understand what I'm looking for?

like image 859
bmende Avatar asked Jul 12 '12 17:07

bmende


1 Answers

You cannot store multiple selectors in one selector, but making an array of selectors is a perfectly valid thing to do. The simplest way would be to store string representations of your selectors in an NSMutableArray, and create selectors from strings in the code that iterates over the array.

NSMutableArray *selectorNames = [NSMutableArray array];
if(random requirements)
    [selectorNames addObject:NSStringFromSelector(@selector(moveUp))];
if(random requirements)
    [selectorNames addObject:NSStringFromSelector(@selector(moveDown))];
...
for (NSString *selectorName in selectorNames) {
    SEL nextSelector = NSSelectorFromString (selectorName);
    // Now you can invoke your selector
}

Another options besides selectors would be using blocks. Blocks are very good at encapsulating actions, too, and you do not need to store their target separately.

like image 60
Sergey Kalinichenko Avatar answered Sep 28 '22 11:09

Sergey Kalinichenko