Objective C +如何创建新线程并向其发布消息

use*_*750 2 multithreading objective-c

我在Objective C中创建新线程时遇到问题

- (void) create
{
     NSLog( @"Hello World from create \n" );
     NSThread* evtThread = [ [NSThread alloc] initWithTarget:self
                            selector:@selector( saySomething )
                          object:nil ];

    [ evtThread start ];
}

 - (void) saySomething
 {
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    printf( "Hello world from new thread \n");
    NSLog( @"Hello World from new thread \n" );
    //[pool release]; 
 }
Run Code Online (Sandbox Code Playgroud)

但看起来这个方法似乎并没有被称为.控制台中没有打印任何内容.

zou*_*oul 10

你确定要显式线程控制吗?很可能你没有.GCD怎么样?

- (void) create
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self saySomething];
    });
}
Run Code Online (Sandbox Code Playgroud)

至于你的问题,如果你使用ARC,线程可能会在你返回之后立即释放create,因此它没有机会执行选择器.您必须将线程存储到strong实例变量或类似的东西中.


bey*_*rss 8

尝试以这种方式启动一个线程:

[self performSelectorInBackground:@selector(saySomething) withObject:nil]
Run Code Online (Sandbox Code Playgroud)