我的.h课程中有以下内容:
extern CGFloat tableMarginSide;
extern CGFloat tableMarginTop;
extern CGFloat fromImageSize;
extern CGFloat keyboardHeightPortrait;
extern CGFloat keyboardHeightLandscape;
在我的初学者中我做了:
CGFloat tableMarginSide = 20;
CGFloat tableMarginTop = 20;
CGFloat fromImageSize = 50;
CGFloat keyboardHeightPortrait = 210;
CGFloat keyboardHeightLandscape = 160;
if (IS_IPAD){
CGFloat tableMarginSide = 80;
CGFloat tableMarginTop = 65;
CGFloat fromImageSize = 50;
CGFloat keyboardHeightPortrait = 260;
CGFloat keyboardHeightLandscape = 350;
}
为什么我收到警告,我不能在班上使用这个浮点数?哦,我不希望顺便使用预处理器
答案 0 :(得分:2)
您正在重新评估init
中具有相同名称的新变量。在init
方法内部,声明是该块的本地。你的意思是:
extern CGFloat tableMarginSide;
extern CGFloat tableMarginTop;
extern CGFloat fromImageSize;
extern CGFloat keyboardHeightPortrait;
extern CGFloat keyboardHeightLandscape;
CGFloat tableMarginSide = 20;
CGFloat tableMarginTop = 20;
CGFloat fromImageSize = 50;
CGFloat keyboardHeightPortrait = 210;
CGFloat keyboardHeightLandscape = 160;
@interface ...
- (id)init {
self = [super init];
if (self) {
if (IS_IPAD)
tableMarginSide = 80;
tableMarginTop = 65;
fromImageSize = 50;
keyboardHeightPortrait = 260;
keyboardHeightLandscape = 350;
}
}
}
尽管如此,这正是nib文件和故事板旨在解决的问题。
即使没有nib文件,我也会避免这种方法。它非常依赖于确保在访问这些全局变量之前调用init
(如果你不是非常小心的话,这很容易发生)。更好的方法是为这些创建类或实例方法,而不是创建“伪常量”(由于它们在运行时发生变化,因此它们不是真正的常量)。