Calling a function delayed in objective-c without a 2nd thread
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 stringWit开发者_C百科hContentsOfFile: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
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;
}
精彩评论