public
Last active

Provide before/after aspects on Cocoa objects (for http://stackoverflow.com/questions/9267727/)

  • Download Gist
main.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.