I am having a bit of trouble understanding this piece of code. It is from a book I am reading but I feel like the guy is just telling me to type stuff without explaining it in m
Your problem is that you don't understand C. Objective-C is a thin layer over C that adds classes and messaging. Check a good C book, such as one from "The Definitive C Book Guide and List".
Without obtaining a reference to the object that is typed as UISlider *
, you would be unable to use the property syntax without, at each instance, casting the sender
reference to the desired type, for example, ((UISlider *)sender).value
. Even if you weren't using property dot notation, a cast would also be necessary to get the compiler to treat [slider value]
as returning anything other than an id
.
The book as is just being silly, though. There's no requirement that the argument to an action method be typed as id
. When you know that the sender is always going to be of a certain type – as in this case, where the code assumes that sender
is always going to be a kind of UISlider
– you can just use that type in the method declaration:
- (IBAction)sliderChanged:(UISlider *)sender
{
/* code */
}
This better documents the programmer's intent – documentation that Interface Builder picks up on – as well as completely eliminating the need to do any casting within the method.
In general, if you need to typecast, there's a good chance you're doing something wrong.
As another example, let's look at this line:
int progressAsInt = (int)(slider.value + 0.5f);
Here, the explicit int
typecast is unnecessary. Because the assignment is to an int
lvalue, the floating point value that results from the addition would necessarily be coerced to an int
as part of the assignment.