0

I've put a NSMattrix on a NSWindow. This NSMattrix contains 2 radio buttons.

I declared 3 IBOutlets: - One for the NSMattrix - One for each radio button (NSButtonCell).

I declared 1 IBAction method: I've linked this same method on each radio button ant on the NSMattrix. This method is automatically called when i change the state o radio button. Great. But when i want to know the state of each radio button in this method, the state is not good.

How should i do to get the state of each radio button in a event method ?

Thanks

Jonas
  • 121,568
  • 97
  • 310
  • 388
testpresta
  • 429
  • 5
  • 15

2 Answers2

1

If you have everything connected via IBOutlets, you can simply query the two buttons for their state whenever you want (as long as your View Controller is the one that owns these outlets, or those outlets are exposed them via @property accessors).

Assuming buttonOne and buttonTwo are IBOutlet NSButtons, you can simply do:

- (IBAction) buttonAction: (id) sender
{
    BOOL buttonOneIsOn = ([buttonOne state] == NSOnState);
    BOOL buttonTwoIsOn = ([buttonTwo state] == NSOnState);
}

NSCell (which NSButtonCell descends from) has a very handy state method. I've linked the documentation for you.

koen
  • 5,383
  • 7
  • 50
  • 89
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Thanks for your answer. This is what i done. But Booleans are not updated. I get the "old" state of radio button – testpresta Jun 28 '12 at 06:33
0

For cases like this I strongly recommend using Cocoa Bindings; this is actually one of the simpler ways to use bindings.

With bindings, user interface synchronization is handled for you. This means that you don't really need to query the state of a radio button; you just query the property that the button is bound to.

Instead of implementing action methods, you only need properties. For instance, - (BOOL) radio1;, - (void) setRadio1:(BOOL) flag;, - (BOOL) radio2; and - (void) setRadio2:(BOOL) flag; (but give the methods better names than that). You can use @property for these in later versions of Objective-C. Put BOOL fields in your class for each one.

Properties can be assigned to radio buttons when you're editing your NIB/XIB file.

By the rules of key-value coding, self.radio1 is a path that implicitly means that the methods radio1 and setRadio1 are both called. If you renamed them to something else, adjust the path name accordingly.

When editing your NIB/XIB, select each Button Cell of your NSMatrix in turn and set an appropriate binding:

  • Set the Value binding to "File's Owner" (if that's where the properties are implemented).
  • Use the key path of the appropriate property (self.radio1 or self.radio2, if you had the above example methods).

The NSMatrix is already set up to allow only one value at a time, so the property values will be similarly restricted.

Kevin Grant
  • 5,363
  • 1
  • 21
  • 24