gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:40:02 25 4
gpt4 key购买 nike

我想使用 C 函数而不是 Objective-C 方法来启动一个新线程。我试过了

[NSThread detachNewThreadSelector: @selector(func) toTarget: nil withObject: id(data)];

我在哪里

void func(void *data) {
// ...
}

datavoid *,但我在objc_msgSend 中遇到运行时崩溃,从

调用
-[NSThread initWithTarget:selector:object:]

我能做什么呢?有可能吗?

最佳答案

自己动手:

// In some .h file.  #import to make the extension methods 'visible' to your code.
@interface NSThread (FunctionExtension)
+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data;
-(id)initWithFunction:(void (*)(void *))function data:(void *)data;
@end

// In some .m file.
@implementation NSThread (FunctionExtension)

+(void)startBackgroundThreadUsingFunction:(id)object
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

void (*startThreadFunction)(void *) = (void (*)(void *))[[object objectForKey:@"function"] pointerValue];
void *startThreadData = (void *) [[object objectForKey:@"data"] pointerValue];

if(startThreadFunction != NULL) { startThreadFunction(startThreadData); }

[pool release];
pool = NULL;
}

+(void)detachNewThreadByCallingFunction:(void (*)(void *))function data:(void *)data
{
[[[[NSThread alloc] initWithFunction:function data:data] autorelease] start];
}

-(id)initWithFunction:(void (*)(void *))function data:(void *)data
{
return([self initWithTarget:[NSThread class] selector:@selector(startBackgroundThreadUsingFunction:) object:[NSDictionary dictionaryWithObjectsAndKeys:[NSValue valueWithPointer:function], @"function", [NSValue valueWithPointer:data], @"data", NULL]]);
}

@end

注意:我写了上面的代码,并把它放在了公共(public)领域。 (有时律师喜欢这种东西)它也完全未经测试!

如果你能保证线程入口函数也创建一个,你总是可以删除 NSAutoreleasePool 位......但它是无害的,没有任何速度损失,并且可以任意调用C 函数要简单得多。我会说就把它放在那里。

你可以像这样使用它:

void bgThreadFunction(void *data)
{
NSLog(@"bgThreadFunction STARTING!! Data: %p", data);
}

-(void)someMethod
{
// init and then start later...
NSThread *bgThread = [[[NSThread alloc] initWithFunction:bgThreadFunction data:(void *)0xdeadbeef] autorelease];
// ... assume other code/stuff here.
[bgThread start];

// Or, use the all in one convenience method.
[NSThread detachNewThreadByCallingFunction:bgThreadFunction data:(void *)0xcafebabe];
}

运行时:

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

关于objective-c - C 函数可以用作 Cocoa 中的选择器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1355045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com