I am using CoreDateBooks and the Recipe samples as style guides, but also looking at many other samples and books. Can someone help explain how to correctly write the @selector statement? I see several different styles.
From CoreDataBooks, the add button selector is a single term with no colon, the method is an IBAction and it is declared in the interface.
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addBook)];
...
- (IBAction)addBook {
}
From Recipes, the add button selector is a term followed by a colon, the method uses (void) and (id)sender, and it is not declared in the interface.
UIBarButtonItem *addButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add:)];
...
- (void)add:(id)sender {
Later in Recipes, the Cancel button has yet another syntax. The button selector is followed by a term with no colon, the method uses void but not sender, and again it is not declared in the interface.
UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(cancel)];
...
- (void)cancel {
I understand that add and add: are different, with the second requiring a parameter, but is there a reason for one or the other? And when would I need to place the method name in the interface?
In other words, when I declare my own selector, such as @selector(add) or @selector(cancel), can I simply use the -(void) format and not place it in the interface?
IBActionis typedef’d tovoid. Its only function is to allow Interface Builder to map your interface elements to actions if your interface is in a nib file. It’s declared in your interface file only so Interface Builder can see it. Thus there’s no real difference between- (IBAction)myActionand- (void)myAction.If your action method doesn’t need to know what control/view triggered the action (i.e. it always does the same thing when the action is invoked on the target), you can omit the
(id)senderparameter and pass in a selector without the colon.If you’re not using Interface Builder you don’t have to use the
IBActionformat, and if your methods will only be invoked within the same class then there’s no need to expose them in your header file (nor is there any harm in doing so).