Skip to content

Instantly share code, notes, and snippets.

@simon-engledew
Created June 24, 2010 08:49
Show Gist options
  • Save simon-engledew/451182 to your computer and use it in GitHub Desktop.
Save simon-engledew/451182 to your computer and use it in GitHub Desktop.
Thread invocation with varargs in Objective C
[SEThreadInvocation detachNewThreadSelector:@selector(request:processData:)
toTarget:self
withObjects:request, data, nil];
//
// SEThreadInvocation.h
//
#import <Foundation/Foundation.h>
@interface SEThreadInvocation : NSObject
{
NSThread * _thread;
NSInvocation * _invocation;
}
@property(nonatomic,retain) NSThread * thread;
@property(nonatomic,retain) NSInvocation * invocation;
- (id) initWithTarget:(id)target selector:(SEL)selector arguments:(NSArray *)arguments;
+ (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObjects:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION;
- (void) start;
@end
//
// SEThreadInvocation.m
//
#import "SEThreadInvocation.h"
@implementation SEThreadInvocation
@synthesize thread = _thread;
@synthesize invocation = _invocation;
- (id) initWithTarget:(id)target selector:(SEL)selector arguments:(NSArray *)arguments
{
if (self = [super init])
{
_thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
_thread.name = @"SEThreadInvocation";
NSMethodSignature * signature = [target methodSignatureForSelector:selector];
self.invocation = [NSInvocation invocationWithMethodSignature:signature];
[_invocation setTarget:target];
[_invocation setSelector:selector];
NSInteger i = 2; // self, _cmd, ...
for (id argument in arguments)
{
[_invocation setArgument:&argument atIndex:i++];
}
[_invocation retainArguments];
}
return self;
}
- (void)start
{
[_thread start];
}
- (void)run
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[_invocation invoke];
[pool release];
}
+ (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObjects:(id)firstObject, ...
{
NSMutableArray * arguments = [NSMutableArray array];
if (firstObject)
{
[arguments addObject:firstObject];
id argument;
va_list objectList;
va_start(objectList, firstObject);
while (argument = va_arg(objectList, id))
{
[arguments addObject:argument];
}
va_end(objectList);
}
SEThreadInvocation * threadInvocation = [[SEThreadInvocation alloc] initWithTarget:target selector:selector arguments:arguments];
[threadInvocation start];
[threadInvocation autorelease];
}
- (void) dealloc
{
[_invocation release];
[_thread release];
[super dealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment