3

I have a UIButton and I am trying to call 2 different actions from one UIButton event, since that button needs to do two things, but I need to do them in a certain order.

No matter how I try, I can't seem to change the order in which the Actions fire. Is there a way for me to decide this, or is it random?

In what order do IBActions get fired from the same component? Is there a way to call them in a certain order?

Dummy Code
  • 1,858
  • 4
  • 19
  • 38

3 Answers3

7

Why not create a single, new method that is called by the button and runs your existing methods exactly the way you want?

Alex
  • 1,625
  • 12
  • 18
2

The answer to this is quite simple, all be it a bit strange. IBActions are called in alphabetical order. See below for an example.

Below are 6 IBAction methods all printing out which method they are.

In the .h file...

- (IBAction)a:(id)sender;
- (IBAction)b:(id)sender;
- (IBAction)c:(id)sender;
- (IBAction)d:(id)sender;

And in the .m file...

- (IBAction)a:(id)sender {
   NSLog(@"a");
}
- (IBAction)b:(id)sender {
   NSLog(@"b");
}
- (IBAction)c:(id)sender {
   NSLog(@"c");
}
- (IBAction)d:(id)sender {
   NSLog(@"d");
}

When I tap on the button linked to all these I get the following log...

2013-06-05 18:06:52.637 TestIBAction[49798:c07] a
2013-06-05 18:06:52.637 TestIBAction[49798:c07] b
2013-06-05 18:06:52.637 TestIBAction[49798:c07] c
2013-06-05 18:06:52.637 TestIBAction[49798:c07] d

If you look at them by alphabetical order they are being fired as follows; a, b, b, d, e, f producing the log shown. Even if you re-arranged the IBActions or link them differently the same log is produced.

The simple answer to this problem is to add letters before your method names such as aOne, bTwo, cThree and then they will be called in that order, whereas if you left them One, Two, Three they would be called as one, three, two due to this alphabetical order.

Hope this helps people. It had me stumped for the longest time.

Dummy Code
  • 1,858
  • 4
  • 19
  • 38
  • Cool, didn't know this! However, I think that Alex's answer above is the way for you to go! – Groot Jun 06 '13 at 00:37
  • @Filip Yes, I do believe that that would be the best way to go however, I felt like sharing something I learned today. :) – Dummy Code Jun 06 '13 at 01:30
  • While this is an interesting discovery, please do not rely on this. It is an undocumented implementation detail that could change. – rmaddy Jun 06 '13 at 04:25
-1

The order is indeterminate and you should not rely on the order as it may change in a future OS update.

darrensi
  • 29
  • 1
  • @HenryHarris This is not wrong. Just because the current implementation appears to call the selectors in alphabetical order does not mean you should rely on this behavior. It is not documented and it could change, just as "darrensi" stated. Never rely on undocumented implementation details. – rmaddy Jun 06 '13 at 04:24
  • This isn't an answer, nor is it helpful. – davidrayowens Apr 17 '14 at 23:48