Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.