简体   繁体   中英

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;
}

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM