0

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;
}
Sam
  • 31
  • 1
  • 6

1 Answers1

0

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];
  • I don't understand, could you please explain this? – Sam Jan 16 '17 at 12:58
  • I misunderstood your question looking at your error log. The exception probably comes since this is not thread safe, multiple threads might be trying to access the item at the same time. There are multiple similiar questions here about this you should search through with good answers. have a look at this for example: http://stackoverflow.com/questions/12091212/understanding-nsrunloop –  Jan 16 '17 at 13:11
  • I want to understand thread in objective-c by making a race game like turtle and rabbit racing program. It is not just like thread in java that easy to use. I think I need to learn more about this. Thank you very much. – Sam Jan 17 '17 at 00:48