Search code examples
objective-cnsthreadgnustep

Objective-c Loop in NSThread


I want to build a object that can run a loop in thread. When I run a loop in thread using NSThread, sometimes works fine and sometimes the error message appear :

Uncaught exception NSInvalidArgumentException, reason: Tried to add nil value for key 'NSArgumentDomain' to dictionary. 

How do I fix it? Or NSthread tutorial can be helpful.

#import <Foundation/Foundation.h>

@interface ThreadTest: NSObject

-(void) run;

-(void) goThread;

@end


@implementation ThreadTest

-(void) run {

    @autoreleasepool {
        int i;
        for (i = 1; i < 5; i++) {
            NSLog (@"Bar");
        }

        NSLog (@"end of loop");
    }
}

-(void) goThread {
    [NSThread detachNewThreadSelector: @selector(run)
                             toTarget: self
                           withObject: nil];
}


int main(void) {
    @autoreleasepool {
        ThreadTest *t = [[ThreadTest alloc] init];
        [t goThread];
    }

    return 0;
}

Solution

  • NSDictionary crashes if you try to insert NIL to it. However, you can insert NSNULL argument to it.

    So just make a check if your object is nil, insert NSNULL instead.

    controlObject != nil ? controlObject : [NSNull null];