Why (id) sender instead of sender (UIButton *)

I’m trying to learn about Objective-C for iPhone development, and while looking at action examples, I often saw things like:

- (IBAction)sliderMoved:(id)sender
{
    UISlider *aSlider = (UISlider *)sender;
    //rest of code goes here...
}

What is the purpose of entering the type (id) and then casting it immediately (UISlider *). Why not just do the following:

- (IBAction)sliderMoved:(UISlider *)aSlider;
{
    //rest of code goes here...
}

Is there a technical reason for this, or is it just an agreement or made for readability?

Thanks in advance,

  • Timo
+3
source share
4 answers

I believe this is an agreement based on the fact that there is not always a 1: 1 comparison between UIControl and IBAction. For example, you might have UISwitch, UIButton, and UITextField, all mapped to a method - (IBAction)syncUI:(id)sender;. In this case, it is not possible to specify the type.

, , , , , , . .

+6

UIButton*, , , - . , , . , , , id .

, , , , , , .

+3

IBActions , , id. sender , , , sender, , .

+2

id - . , , .., , . , , , , ( ToSelector:).

0

All Articles