롤 자신 :
// 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
참고 : 나는 공공 영역에서 발생 그것에 의해 여기에 위의 코드를 썼다. (때로는 이런 종류의 물건을 좋아하는 변호사) 완전히 테스트되지 않았습니다!
당신이 스레드 항목 기능은 하나를 만드는 보장 할 수 있다면 당신은 항상 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];
}
실행하면 :
그리고 당신과 같이 사용할 수 있습니다 당신은 NSThread
물건이 필요하지 않은 경우
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
+1 Obj-C 카테고리는 때로는 매우 유용합니다. – u0b34a0f6ae
좋은 생각, 고마워! –
'dispathc_async_f()'가 위험 할 수있는 반면,이 모든 것을 수행하고 자신의 구현을 롤업하는 것은 별다른 의미가 없습니다. Apple 엔지니어에게 스레딩 구현을 맡기는 것이 좋습니다. 그들은 아마도 그들의 시스템에서 일어나는 일을 더 잘 이해할 것입니다. –