Skip to content

Instantly share code, notes, and snippets.

@jamztang
Created October 2, 2011 17:37
Show Gist options
  • Save jamztang/1257681 to your computer and use it in GitHub Desktop.
Save jamztang/1257681 to your computer and use it in GitHub Desktop.
Using NSProxy to perform operation on main thread easily
//
// JTMainQueueProxy.h
//
// Created by James Tang on 02/10/2011.
//
#import <Foundation/Foundation.h>
@interface JTMainQueueProxy : NSProxy {
id _proxiedTarget;
}
+ (id)proxy;
- (id)prepareInvocationWithTarget:(id)target;
@end
//
// JTMainQueueProxy.m
//
// Created by James Tang on 02/10/2011.
//
#import "JTMainQueueProxy.h"
@implementation JTMainQueueProxy
- (id)init {
return self;
}
- (void)dealloc {
[_proxiedTarget release];
[super dealloc];
}
#pragma mark Instance method
- (id)prepareInvocationWithTarget:(id)target {
[_proxiedTarget autorelease], _proxiedTarget = nil;
_proxiedTarget = [target retain];
return self;
}
#pragma mark NSProxy
- (void)forwardInvocation:(NSInvocation *)invocation {
[invocation setTarget:_proxiedTarget];
[invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:YES];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [_proxiedTarget methodSignatureForSelector:sel];
}
#pragma mark Class Methods
+ (id)proxy {
JTMainQueueProxy *proxy = [[JTMainQueueProxy alloc] init];
return [proxy autorelease];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment