【发布时间】:2011-04-26 08:47:24
【问题描述】:
这是我的情况 - 让我们看看是否有任何编码天才可以帮助我!
我的情况是这样的:
我有一个整数存储在 NSUserDefaults 中,名称为 @"scifi1" - 它可能是……比如说 250 多个值之一 - 非连续的,但都是已知的(即它来自多项选择)
我需要检查所述整数的值,并根据它执行不同的操作。
现在,我的代码就是这样
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"scifi1"] == 040){
[self spaceup];
}
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"scifi1"] == 10040){
[self spaceup];
[self ctrlup];
}
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"scifi1"] == 20040){
[self spaceup];
[self altup];
}
虽然这行得通,但一旦你添加了几十个代码,代码就会变成 a) 很长 b) 当为几种不同的方法完成时,iPhone 无法合理处理太长,事实上 Xcode 会抛出一个 GCC 4.2 错误告诉我。
那么检查这个的最好方法是什么?必须有更好的方法然后重复'if'语句。
我尝试设置 switch/case 样式设置,但由于整数不是常量,它似乎对此不满意 - 老实说,从长远来看,我不确定 switch/case 是否会更好而不是拥有多个 if 语句。
有人有什么好主意吗?
编辑:
好的,我已经尝试过这个作为实验。
-(void)checkandrunup {
if (tempInt == 040){
[self spaceup];
}
if (tempInt == 10040){
[self spaceup];
[self ctrlup];
}
if (tempInt == 20040){
[self spaceup];
[self altup];
}
if (tempInt == 30040){
[self spaceup];
[self shiftup];
}}
-(IBAction)torpup{
//If to check for edit and display popover
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"viewEdit"] == YES) {
}
else {
NSInteger tempInt = [[NSUserDefaults standardUserDefaults] integerForKey:@"scifi1"];
}
//First Sound
if([[NSUserDefaults standardUserDefaults] boolForKey:@"viewHidden"] == YES) {
NSString *path = [NSString stringWithFormat:@"%@%@",
[[NSBundle mainBundle] resourcePath],
@"/beep1.WAV"];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID); }
//Second Sound
else {
NSString *path = [NSString stringWithFormat:@"%@%@",
[[NSBundle mainBundle] resourcePath],
@"/beep2.WAV"];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
}
}
但是 tempInt 没有从 Torpup 传递到 checkandrunup - 有没有办法让这种情况发生?
【问题讨论】:
-
我还没有得到准确的报价,但我知道它不会对它正在检查的 if 的数量感到满意。如果按照您的回答,如果我想知道这是否会让它更快乐,我会使用 else...应该尝试。
标签: ios xcode if-statement