How to use [performSelector: onThread: withObject: waitUntilDone:]?

I tried to subclass NSThread to control the flow with some data. I want to simulate join () in python, according to the doc:

join (): Wait for the thread to complete. This blocks the calling thread until the thread whose join () method is called terminate

So, I think using performSelector: onThread: withObject: waitUntilDone: YES will be fine, but that will not work. It just does nothing and does not exit, it works as always.

This is my code:

@interface MyClass : NSThread
@property (strong, nonatomic) NSMutableArray *msgQueue;
@property (assign, nonatomic) BOOL stop;
@end

@implementation MyClass

-(id)init
{
    self = [super init];
    if (self) {
        self.msgQueue = [NSMutableArray array];
        self.stop = NO;
        [self start];
        return self;
    }
    return nil;
}

-(void)myRun
{
    while (!self.stop) {
        NSLock *arrayLock = [[NSLock alloc] init];
        [arrayLock lock];
        NSArray *message = [self.msgQueue firstObject];
        [self.msgQueue removeObjectAtIndex:0];
        [arrayLock unlock];
        NSLog(@"%@", message);
        if ([message[0] isEqualToString:@"terminate"]) {
            self.stop = YES;
        }
    }
}

-(void)join
{
    [self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        MyClass *a = [[MyClass alloc] init];
        [a.msgQueue addObject:@[@"terminate",@"hello world"]];
        //[a myRun];   // this line works so the myRun method should be good,
        [a join];      // but I want this line work, and I have no idea what the problem is.
    }
    return 0;
}
+3
source share
2 answers

From Apple's documentation on performSelector:onThread:withObject:waitUntilDone::

, , , NSRunLoopCommonModes. ( , ) .

, , myRun, .

Merlevede, myRun , join. join , myRun . . Apple :

, YES , . NO, , . , .

, , , , , performSelector: .

+1

.

-(void)join
{
    [self performSelector:@selector(myRun) onThread:self withObject:nil waitUntilDone:YES];
}

join myRun ( waitUntilDone), myRun , join, join.

performSelector:onThread:withObject:waitUntilDone: .

0

All Articles