• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Using non-id sender in IBAction methods
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Using non-id sender in IBAction methods


  • Subject: Re: Using non-id sender in IBAction methods
  • From: Uli Kusterer <email@hidden>
  • Date: Sun, 7 Jun 2009 16:05:36 -0700

Am 07.06.2009 um 08:45 schrieb Marc Liyanage:
With the new dot notation I sometimes use explicit types in my IBAction methods:

- (IBAction)doSomething:(UIButton *)button ...

instead of

- (IBAction)doSomething:(id)sender ...

so I don't have to downcast "sender" to be able to use the dot notation.

Do others do this too? Is this discouraged for some reason?


Not a good idea. The sender can be pretty much any object. It might not be right now, but IBActions are often hooked up to several objects, like a toolbar item, a pushbutton and a menu item. Hence the definition as "id". By leaving it as "id" and then typecasting, the assumption becomes explicit in the code. By having it as another type right away, you're kind of masking the issue.

 I recommend you write it as:

-(IBAction) doSomething: (id)sender
{
    NSAssert( [sender isKindOfClass: [UIButton class]] );
    UIButton*    senderBtn = (UIButton*)sender;

    // use btn here...
}

Or at least put an assert in there if you feel you need an IBAction with a non-ID parameter type. The details of the assert are not as important. In fact, if you can, use [sender respondsToSelector: @selector(whateverYouAreCalling:)] or so instead of -isKindOfClass:. The point of the assert is to make your code fail in a noticeable way when someone breaks the assumptions it makes.

Cheers,
-- Uli Kusterer
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de





_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


  • Follow-Ups:
    • Re: Using non-id sender in IBAction methods
      • From: Bryan Henry <email@hidden>
References: 
 >Using non-id sender in IBAction methods (From: Marc Liyanage <email@hidden>)

  • Prev by Date: Re: NSOutlineView and tags...
  • Next by Date: How to detect a click on app's dock icon (when the app is active)?
  • Previous by thread: Re: Using non-id sender in IBAction methods
  • Next by thread: Re: Using non-id sender in IBAction methods
  • Index(es):
    • Date
    • Thread