-1

in macos/xcode/Objective-c as shown in below, need to program execution stop till the thread method that it started is finishes and returns. line "All done" should show up at the end of program output after main program executed successfully. Have tried the code in below in macos/xcode/Objective-c console application. The error I am getting is:

**** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector*

the code that I have tried is:

#import <Foundation/Foundation.h>

NSThread *thrd;

@interface MyObject : NSObject
-(void) loop;
-(void) func1;
-(void) func2;
@end

@implementation MyObject
-(void) loop{

    int c;
    for(c=0;c<100;++c)
    {
        printf("%i\n",c);
    }
}

-(void) func1
{
    [NSThread detachNewThreadSelector:@selector(func2) toTarget:self withObject:nil];
    while (1)
    {
        if ([[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]])
        {
            NSLog(@"done with func2");
            break;
        }
    }

}

-(void) func2
{
    sleep(2);
    [self performSelector:@selector(loop) onThread:thrd withObject:nil waitUntilDone:YES modes:@[NSDefaultRunLoopMode]];

}
@end

int main(int argc, char *argv[])
{
    thrd = [[NSThread alloc] initWithTarget:[MyObject class] selector:@selector(func1) object:nil];
    [thrd start];
    
    printf("All done\n");
    return 0;
}
  • I recommend to start and stop the runloop explicitly and perform the delay with GCD. `while` and `sleep` are discouraged. – vadian Jun 04 '22 at 10:05
  • is there a working example of that approach?. – fra87kdk Jun 04 '22 at 13:54
  • In Swift it's basically [this](https://stackoverflow.com/questions/43825263/how-to-exit-a-runloop/43825447#43825447). – vadian Jun 04 '22 at 15:02
  • in windows there is PeekMessage, etc. to prevent UI lock up during long loops in the called library. What is the equivalent of that in macos, objective-c?. Or, maybe the APPs in Macos does not have such problem?. – fra87kdk Jun 04 '22 at 16:15

0 Answers0