【问题标题】:Calling a function delayed in objective-c without a 2nd thread在没有第二个线程的情况下调用objective-c中延迟的函数
【发布时间】:2011-04-04 18:49:12
【问题描述】:

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

- (void) 模拟流 { NSArray *句子; 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]]; }}

感谢您的帮助。问候

【问题讨论】:

  • -performSelector:withObject:afterDelay: 有什么问题?
  • 感谢您的评论。请看我的“答案”

标签: objective-c function timer call delay


【解决方案1】:

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

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

【讨论】:

  • 非常感谢。那是个好主意 :) 系统在后台运行这个调用需要做很多工作吗?这些方法不执行复杂的操作,所以我想应该没问题.. ?!
猜你喜欢
  • 1970-01-01
  • 2012-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
相关资源
最近更新 更多