[英]Using NSTimer with two intervals
我正在創建一個將文本轉換為摩爾斯電碼,然后使用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;
我發現了一個腳本,該腳本可以使用NSTimer以可調的間隔打開和關閉iPhone的手電筒。 但是我不知道如何添加兩個不同的間隔,一個用於點,一個用於摩斯破折號。
- (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的新手。
您可以嘗試在背景樹上依次運行代碼,並根據需要將其休眠。 與使用大量計時器相比,編寫和維護代碼要容易得多。
// 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];
// ...
}
我會嘗試做一個遞歸函數:
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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.