简体   繁体   English

NSThread中的Objective-c循环

[英]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 : 当我使用NSThread在线程中运行循环时,有时工作正常,有时会出现错误消息:

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. 或NSthread教程可能会有所帮助。

#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. 如果尝试向其中插入NIL,则NSDictionary崩溃。 However, you can insert NSNULL argument to it. 但是,您可以向其插入NSNULL参数。

So just make a check if your object is nil, insert NSNULL instead. 因此,只需检查您的对象是否为nil,则插入NSNULL即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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