开发者

iPhone UISlider action method

In the current book I am reading, the author implements an IBAction for a slider in the following way (see below V001). To my eye, it seemed a little over complicated so I re-factored the code (V002). Am I right in thinking that sender is a pointer to the object that fired the event? Also, is there any downside to casting sender in the header, rather than leaving it as sender and casting it in the method bo开发者_运维技巧dy?

v001

-(IBAction)sliderChange:(id)sender {
    UISlider *slider = (UISlider *)sender;
    int progressAsInt = (int)([slider value] + 0.5f);
    NSString *newText = [[NSString alloc] initWithFormat:@"%d", progressAsInt];
    [sliderLabel setText:newText];
    [newText release];      
}

v002

-(IBAction)sliderChange:(UISlider*)sender {
    NSString *newText = [[NSString alloc] initWithFormat:@"%d",(int)[sender value]];
    [sliderLabel setText:newText];
    [newText release];
}

gary


id a special type that can hold any object. The nuance is that you don't have well-defined type safety. You can call any selector on any object, and if it exists it will be invoked.

In V001, doing [slider value] instead of [sender value] makes more logical sense which I think is probably why you took to refactoring in the first place because it didn't appear to be called.

In V002 [sender value] retrieves the float property of the same UISlider but hides the fact that you may not be getting a a slider object, and it could be on any object.

This is a matter of style and discrimination. I am pretty diligent in my own code to determine which concrete object I am trying to access a selector, and will even go so far as calling isKindOfClass, and verifying I am calling the selector on the correct UISlider object. To answer your downside question: the type of the object isn't obviated as it should be when using id.

Why? I want multiple sliders on the same view handling the slider event, I don't want one slider to impact the data of both, even if I may want to handle them in the same way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜