Objective C NSThread 和匿名函数

发布于 2024-10-12 11:19:53 字数 587 浏览 3 评论 0原文

尝试将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人的夜不怕黑 2024-10-19 11:19:53

要使用 NSThread API,您必须有一个对象和一个选择器。虽然块在技术上是一个对象,但它没有任何可以调用的方法。因此,您无法在 action 参数中传递任何内容来实现此操作。

如果您想异步执行块,有几种方法可以实现:

  • 使用 Grand Central Dispatch 的 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 the action parameter that would make this work.

If you want to execute a block asynchronously, there are a couple ways you can do it:

  • Use Grand Central Dispatch's dispatch_async() function, or one of the appropriate variants.
  • Give the block to an NSBlockOperation, and hand that off to an NSOperationQueue.
  • Create a method on an object that takes a block parameter and simply executes it, and then pass that object and selector, along with the block, to the NSThread API. Don't forget to -copy the block first, or you'll probably crash.
青衫负雪 2024-10-19 11:19:53

但事实并非如此。选择器是方法的名称,而块不是方法,因此不能使用选择器来调用块。如果你想在后台执行一个块,你可以使用NSBlockOperationdispatch_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 or dispatch_async().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文