怎么#define不需要指定变量类型?

时间:2012-05-03 02:11:16

标签: objective-c

为什么这段代码有效?

// in a constants file:

#define ADFadeOutSpeed 1.1



// then, later, in another file:

-(void)fadeOut:(UIView *)sender{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:ADFadeOutSpeed];
    sender.alpha = 0.0;
    [UIView commitAnimations];
}

我原以为编译器会抱怨ADFadeOutSpeed没有强类型。

3 个答案:

答案 0 :(得分:6)

因为#define没有创建变量或对象,所以它是一个编译器命令,用'替换所有foo实例' - 所以正在发生的事情,精确地退出,是ADFadeOutSpeed是每次在代码中显示时为1.1。编译器没有看到:

[UIView setAnimationDuration:ADFadeOutSpeed];

它看到了

[UIView setAnimationDuration:1.1];

答案 1 :(得分:3)

预处理时只是文本替换。也就是说,在编译发生之前替换文本。

答案 2 :(得分:2)

#define是C预编译器宏而不是变量。您指定在编译代码之前,字符串ADFadeOutSpeed将替换为字符串1.1。你没有得到编译器警告,因为就编译器本身而言,它正在评估的表达式是[UIView setAnimationDuration:1.1];,并且它将1.1解释为文字。

相关问题