我正在创建一个将文本转换为摩尔斯电码的应用,然后使用iPhone的手电筒将其闪现。我使用字符串替换,将NSString的内容转换为摩尔斯电码。
// some of the code :
str = [str stringByReplacingOccurrencesOfString:@"5" withString:n5];
str = [str stringByReplacingOccurrencesOfString:@"6" withString:n6];
str = [str stringByReplacingOccurrencesOfString:@"7" withString:n7];
str = [str stringByReplacingOccurrencesOfString:@"8" withString:n8];
str = [str stringByReplacingOccurrencesOfString:@"9" withString:n9];
str = [str stringByReplacingOccurrencesOfString:@"0" withString:n0];
NSString *morseCode = [[NSString alloc] initWithFormat:str];
self.label.text = morseCode;
我找到了一个脚本,可以打开和关闭iPhone的手电筒,使用NSTimer可调节间隔。但我无法弄清楚如何添加两个不同的间隔,一个用于点,一个用于莫尔斯破折号。
- (void)viewDidLoad
{
[super viewDidLoad];
int spaceTime;
spaceTime = 1;
int dashTime;
dashTime = 2;
int dotTime;
dotTime = 0.8;
strobeIsOn = NO;
strobeActivated = NO;
strobeFlashOn = NO;
flashController = [[FlashController alloc] init];
self.strobeTimer = [
NSTimer
scheduledTimerWithTimeInterval:spaceTime
target:self
selector:@selector(strobeTimerCallback:)
userInfo:nil
repeats:YES
];
self.strobeFlashTimer = [
NSTimer scheduledTimerWithTimeInterval:dotTime
target:self
selector:@selector(strobeFlashTimerCallback:)
userInfo:nil
repeats:YES
];
}
- (void)strobeTimerCallback:(id)sender {
if (strobeActivated) {
strobeIsOn = !strobeIsOn;
// ensure that it returns a callback. If no, returns only one flash
strobeFlashOn = YES;
} else {
strobeFlashOn = NO;
}
}
- (void)strobeFlashTimerCallback:(id)sender {
if (strobeFlashOn) {
strobeFlashOn = !strobeFlashOn;
[self startStopStrobe:strobeIsOn];
} else {
[self startStopStrobe:NO];
}
}
我应该使用两个定时器,还是可以使用不同的定时器?我应该将字符串的内容放在一个数组中吗? 我是Obj-C的新手..
答案 0 :(得分:0)
您可以尝试在背景树上按顺序运行代码,并根据需要长时间休眠。编写和维护代码要比使用一堆定时器容易得多。
// execute in background
[self performSelectorInBackground:@selector(doTheMagic) withObject:nil];
- (void)doTheMagic {
NSLog(@"Turn ON");
[NSThread sleepForTimeInterval:1];
NSLog(@"Turn OFF");
[NSThread sleepForTimeInterval:0.1f];
NSLog(@"Turn ON");
[NSThread sleepForTimeInterval:1.0f];
// ...
}
答案 1 :(得分:0)
我会尝试制作一个递归函数:
parseAndFlash
{
NSString *codeString = @"-.-. --- -.. .";
int currentLetterIndex = 0;
//codeString and currentLetterIndex should be declared outside this function as members or something
double t_space = 2, t_point = 0.5, t_line = 1, t_separator = 0.1;
double symbolDuration = 0;
if(currentLetterIndex >= [codeString length])
return;
char currentLetter = [codeString characterAtIndex:currentLetterIndex];
switch (currentLetter) {
case '-':
symbolDuration = t_line;
[self flashOnFor:t_line];
break;
case '.':
symbolDuration = t_point;
[self flashOnFor:t_point];
break;
case ' ':
symbolDuration = t_space;
[self flashOff];
break;
default:
break;
}
currentLetterIndex ++;
symbolDuration += t_separator;
[self performSelector:@selector(parseAndFlash) withObject:nil afterDelay:symbolDuration];
}