在没有第二个线程的情况下调用在objective-c中延迟的函数

时间:2011-04-04 18:49:12

标签: objective-c function timer call delay

我想调用一个函数,即发送一个延迟的句子,以模拟数据流。数据存储在文本文件中。文本文件的每一行包含一个句子。我试图通过使用sleep(x)来获得延迟的调用行为,但这冻结了整个应用程序。我是否必须使用单独的线程,或者是否可以使用NSTimer或某些线程。比如[self performSelector:@selector(parseSentence :) withObject:s afterDelay:2]?

- (void) simulateStream
{
    NSArray *sentences;

NSString *path = [[NSBundle mainBundle] pathForResource:@"Sentence_File" ofType:@"txt"]; NSString *st; if (path) { st=[NSString stringWithContentsOfFile:pfad encoding:NSUTF8StringEncoding error:nil]; sentences=[[st substringFromIndex:[st rangeOfString:@"$"].location+1] componentsSeparatedByString:@"$"]; } for(int i=0; i<[sentences count]; i++) { //----CALL THIS WITH A DELAY OF 2 SECONDS---- [sentenceHandler parseSentence:[sentences objectAtIndex:i]]; }}

感谢您的帮助。问候

1 个答案:

答案 0 :(得分:0)

您可以增加每次传递的延迟间隔:

NSTimeInterval delay = 2;
for (NSString* sentence in sentences) {
   [sentenceHandler performSelector:@selector(parseSentence:)
                         withObject:sentence
                         afterDelay:delay];
   delay += 2;
}