views:

127

answers:

3

In the code below, do I need to cast sender to UISlider? I can't really see the reason as sender is a UISlider object anyways?

-(IBAction)sliderChangeGoat:(id)sender {
    UISlider *slider = sender; // OR UISlider *slider = (UISlider*)sender;
    NSString *newText = [[NSString alloc] initWithFormat:@"%d", (int)[slider value]];
    [sliderLabel_003 setText:newText];

    if((int)[slider value] > 0) [goatLabel setText:@"Goats:"];
    } else [goatLabel setText:@"None:"];

    [newText release];
}

EDIT_001:

Thats what I was thinking (@chuck), do you mean? I was not sure if it was bad form to change the name sender?

-(IBAction)sliderChangeGoat:(UISlider*)slider {
}

many thanks

gary

+1  A: 

Casting it explicitly may help the compiler confirm your intent. If you are seeing compiler warnings, then go ahead and cast.

darren
the irony is, you won't *get* compiler warnings when messaging `id`, only runtime errors. If you type statically, then the compiler can warn you, since it better understands your intent.
Quinn Taylor
That's a good point Quinn. Thanks for clarifying.
darren
You might get warnings when you use `id` but not with an explicit static type if there are multiple conflicting definitions for a method (e.g. `setSomething:(NSNumber *)num` and `setSomething:(NSInteger)num`). But in general, the compiler will complain at you more with a statically typed variable — that's the whole point in doing it.
Chuck
Good clarification, Chuck. I of course meant warnings of this type, but it's certainly possible to get warning when using `id` as you point out. I've seen those on occasion myself.
Quinn Taylor
+2  A: 

It makes no difference. id is equivalent to any other object pointer type. All using a more specific type does is allow the compiler to check what its properties are and that you're sending the object messages its declared class responds to.

If you do want to statically type it that way, you can just make the argument itself (UISlider *)slider. The argument name is just like any other argument name — it's just a variable. I often change it to "unused" in delegate methods where I don't care about the sender just to make it explicit that it won't change if I hook something else up to it. And as I said, UISlider* is the same as id except it limits what messages you can send without getting a warning.

Chuck
A: 

Objective-C is a dynamic language. At runtime, it will try to send the sender the value message. If your sender is a UISlider it will work. Like the others said, if you are seeing a warning go ahead and change the method declaration or cast the sender, but it will work even if you don't do this.

David Kanarek