Skip to content

Instantly share code, notes, and snippets.

@georgf
Created February 15, 2012 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgf/1836331 to your computer and use it in GitHub Desktop.
Save georgf/1836331 to your computer and use it in GitHub Desktop.
Provide before/after aspects on Cocoa objects (for http://stackoverflow.com/questions/9267727/)
#import <Foundation/Foundation.h>
@interface AspectProxy : NSProxy {
id target_;
}
- (id)initWithTarget:(id)target;
@end
@implementation AspectProxy
- (id)initWithTarget:(id)target {
target_ = [target retain];
return self;
}
- (void)dealloc {
[target_ release];
[super dealloc];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [target_ methodSignatureForSelector:sel];
}
- (void)forwardInvocation:(NSInvocation *)inv {
SEL sel = [inv selector];
NSLog(@"forwardInvocation for: %@", NSStringFromSelector([inv selector]));
if (sel == @selector(aspectBefore:) || sel == @selector(aspectAfter:)) {
return;
}
if ([target_ respondsToSelector:@selector(aspectBefore:)]) {
[target_ performSelector:@selector(aspectBefore:) withObject:inv];
}
[inv invokeWithTarget:target_];
if ([target_ respondsToSelector:@selector(aspectAfter:)]) {
[target_ performSelector:@selector(aspectAfter:) withObject:inv];
}
}
@end
@interface Test : NSObject
@property (nonatomic, copy) NSString *text;
- (void)someFunction;
@end
@implementation Test
@synthesize text;
- (id)init {
if (self = [super init]) {
return [[AspectProxy alloc] initWithTarget:[self autorelease]];
}
return self;
}
- (void)dealloc {
self.text = nil;
[super dealloc];
}
- (void)aspectBefore:(NSInvocation *)inv {
NSLog(@"before %@", NSStringFromSelector([inv selector]));
}
- (void)aspectAfter:(NSInvocation *)inv {
NSLog(@"after %@", NSStringFromSelector([inv selector]));
}
- (void)someFunction {
NSLog(@"some function called");
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Test *x = [[[Test alloc] init] autorelease];
[x someFunction];
x.text = @"test";
NSLog(@"x.text='%@'", x.text);
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment