Objective C NSThread 和匿名函数
尝试将 NSThread::detachNewThreadSelector 与匿名函数一起使用
void (^testA)(void) = ^
{
NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];
NSLog(@"in threadA",nil);
[oPool release];
};
[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];
当我尝试运行应用程序时,
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'
时出现错误:任何人都可以帮我解决这个问题吗?
Trying to use NSThread::detachNewThreadSelector
with anonymous function
void (^testA)(void) = ^
{
NSAutoreleasePool *oPool = [[NSAutoreleasePool alloc] init];
NSLog(@"in threadA",nil);
[oPool release];
};
[NSThread detachNewThreadSelector:@selector(testA) toTarget:testA withObject:nil];
when I'm trying to run application I got error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSThread initWithTarget:selector:object:]: target does not implement selector (*** -[__NSGlobalBlock__ testA])'
can anyone give me a hand with that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要使用 NSThread API,您必须有一个对象和一个选择器。虽然块在技术上是一个对象,但它没有任何可以调用的方法。因此,您无法在
action
参数中传递任何内容来实现此操作。如果您想异步执行块,有几种方法可以实现:
dispatch_async()
函数,或适当的变体之一。NSBlockOperation
,然后将其交给NSOperationQueue
。NSThread
API。不要忘记先-copy
块,否则你可能会崩溃。To use that
NSThread
API, you mist have an object and a selector. While a block is technically an object, it doesn't have any methods that you can invoke. As such, there's nothing you could pass in theaction
parameter that would make this work.If you want to execute a block asynchronously, there are a couple ways you can do it:
dispatch_async()
function, or one of the appropriate variants.NSBlockOperation
, and hand that off to anNSOperationQueue
.NSThread
API. Don't forget to-copy
the block first, or you'll probably crash.但事实并非如此。选择器是方法的名称,而块不是方法,因此不能使用选择器来调用块。如果你想在后台执行一个块,你可以使用
NSBlockOperation
或dispatch_async()
。It just does not work that way. A selector is the name of a method, and a block is not a method so you can't use a selector to call a block. If you want to execute a block in the background, you can use
NSBlockOperation
ordispatch_async()
.