objective-c – C函数可以用作Cocoa中的选择器吗?

前端之家收集整理的这篇文章主要介绍了objective-c – C函数可以用作Cocoa中的选择器吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用C函数启动一个新线程,而不是使用Objective-C方法.我试过了
  1. [NSThread detachNewThreadSelector: @selector(func) toTarget: nil withObject: id(data)];

我在哪里

  1. void func(void *data) {
  2. // ...
  3. }

和data是一个void *,但我在objc_msgSend中遇到运行时崩溃,调用来自

  1. -[NSThread initWithTarget:selector:object:]

我该怎么做?它甚至可能吗?

@R_502_323@

滚动你自己:
  1. // In some .h file. #import to make the extension methods 'visible' to your code.
  2. @interface NSThread (FunctionExtension)
  3. +(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data;
  4. -(id)initWithFunction:(void (*)(void *))function data:(void *)data;
  5. @end
  6.  
  7. // In some .m file.
  8. @implementation NSThread (FunctionExtension)
  9.  
  10. +(void)startBackgroundThreadUsingFunction:(id)object
  11. {
  12. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  13.  
  14. void (*startThreadFunction)(void *) = (void (*)(void *))[[object objectForKey:@"function"] pointerValue];
  15. void *startThreadData = (void *) [[object objectForKey:@"data"] pointerValue];
  16.  
  17. if(startThreadFunction != NULL) { startThreadFunction(startThreadData); }
  18.  
  19. [pool release];
  20. pool = NULL;
  21. }
  22.  
  23. +(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data
  24. {
  25. [[[[NSThread alloc] initWithFunction:function data:data] autorelease] start];
  26. }
  27.  
  28. -(id)initWithFunction:(void (*)(void *))function data:(void *)data
  29. {
  30. return([self initWithTarget:[NSThread class] selector:@selector(startBackgroundThreadUsingFunction:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithPointer:function],@"function",[NSValue valueWithPointer:data],@"data",NULL]]);
  31. }
  32.  
  33. @end

注意:我写了上面的代码,并将其放在公共领域. (有时律师喜欢这种东西)它也完全没有经过考验!

你可以随时删除NSAutoreleasePool位,如果你可以保证线程入口函数也创建一个…但它是无害的,没有任何速度惩罚,并使调用任意C函数更简单.我会说保持它在那里.

你可以像这样使用它:

  1. void bgThreadFunction(void *data)
  2. {
  3. NSLog(@"bgThreadFunction STARTING!! Data: %p",data);
  4. }
  5.  
  6. -(void)someMethod
  7. {
  8. // init and then start later...
  9. NSThread *bgThread = [[[NSThread alloc] initWithFunction:bgThreadFunction data:(void *)0xdeadbeef] autorelease];
  10. // ... assume other code/stuff here.
  11. [bgThread start];
  12.  
  13. // Or,use the all in one convenience method.
  14. [NSThread detachNewThreadByCallingFunction:bgThreadFunction data:(void *)0xcafebabe];
  15. }

运行时:

  1. 2009-08-30 22:21:12.529 test[64146:1303] bgThreadFunction STARTING!! Data: 0xdeadbeef
  2. 2009-08-30 22:21:12.529 test[64146:2903] bgThreadFunction STARTING!! Data: 0xcafebabe

猜你在找的C&C++相关文章