Reputation: 26223
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
Upvotes: 1
Views: 1606
Reputation: 12613
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.
Upvotes: 0
Reputation: 237060
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.
Upvotes: 3
Reputation: 15588
Casting it explicitly may help the compiler confirm your intent. If you are seeing compiler warnings, then go ahead and cast.
Upvotes: 1