在变量之前的括号中的类型名称是什么意思? [英] What does a type name in parentheses before a variable mean?

查看:330
本文介绍了在变量之前的括号中的类型名称是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一点麻烦理解这段代码。这是从我正在读的一本书,但我觉得这个家伙只是告诉我输入的东西,而不解释它在很深入。

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 much depth.

- (IBAction)sliderChanged:(id)sender
{
    UISlider *slider = (UISlider *)sender; //set slidervar as active slider
    int progressAsInt = (int)(slider.value + 0.5f);
    NSString newText = [[NSString alloc] initWithFormat:@"%d",progressAsInt];
    sliderLabel.text = newText;
    [newText release];
}

问题出在第一行

UISlider *slider = (UISlider *)sender; //set slidervar as active slider

我不明白什么typecasting是什么,在书里。

I do not understand what typecasting is, which is what the guy says in the book. "avoids needing to typecast sender everytime we use it"

我也不明白为什么第二行有 int 括号中。我习惯了像

I also do not understand what/why the second line has int in brackets. I am used to having code like

int progressAsInt = 56


推荐答案

Typecasting是一种告诉编译器某事是不同类型的方法。它涉及你问题的两个部分。

Typecasting is a method of telling the compiler that something is a different type than it is. It is involved in both parts of your question. You cast something by placing the new type in parentheses before the item you are casting.

UISlider *slider = (UISlider *)sender;

当方法被声明时, sender id 的类型。因为你知道它应该是一个滑块,你把它转换为 UISlider * 并存储在一个变量类型,使编译器不给你警告,当您尝试使用滑块特定的属性。

When the method is declared, sender has a type of id. Since you know it is supposed to be a slider, you cast it to UISlider * and store it in a variable with that type so that the compiler doesn't give you warnings when you try to use slider specific properties.

int progressAsInt = (int)(slider.value + 0.5f);

这里, slider.value 点号。因为你想把它存储在一个整数类型,你需要转换它。当一个float被转换为int时,它会自动向零舍入。代码需要四舍五入到最接近的整数,因此在投放前添加了0.5。

Here, slider.value is a floating point number. Since you want to store it in an integer type, you need to cast it. When a float is cast to an int, it is automatically rounded toward zero. The code wanted it rounded to the nearest integer, so it added 0.5 before casting.

这篇关于在变量之前的括号中的类型名称是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆