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

发布于 2024-10-30 07:16:24 字数 825 浏览 2 评论 0原文

我想调用一个函数,即发送一个句子,延迟,以模拟数据流。数据存储在文本文件中。文本文件的每一行包含一个句子。我尝试通过使用 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]]; }}

感谢您的帮助。问候

I want to call a function, that is sending a sentence, delayed, in order to simulate a stream of data. The data is stored in a textfile. Each line of the textfile contains one sentence. I tried to get a delayed calling behaviour earlier by using sleep(x) but this freezed the whole application. Do I have to use a seperate thread or is it possible to get it working with NSTimer or sth. like [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]]; }}

Thanks for help. Greetings

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弃爱 2024-11-06 07:16:24

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

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

You could increase the delay interval in each pass:

NSTimeInterval delay = 2;
for (NSString* sentence in sentences) {
   [sentenceHandler performSelector:@selector(parseSentence:)
                         withObject:sentence
                         afterDelay:delay];
   delay += 2;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文