main
 1#import "KWCaptureSpy.h"
 2#import "KWObjCUtilities.h"
 3#import "NSInvocation+KiwiAdditions.h"
 4#import "NSMethodSignature+KiwiAdditions.h"
 5#import "KWValue.h"
 6
 7@implementation KWCaptureSpy
 8@dynamic argument;
 9
10- (id)initWithArgumentIndex:(NSUInteger)index {
11    if ((self = [super init])) {
12        _argumentIndex = index;
13        _argumentCaptured = NO;
14    }
15    return self;
16}
17
18- (id)argument {
19    if (!_argumentCaptured) {
20        @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"Argument requested has yet to be captured." userInfo:nil];
21    }
22    return [[_argument retain] autorelease];
23}
24
25- (void)object:(id)anObject didReceiveInvocation:(NSInvocation *)anInvocation {
26    if (!_argumentCaptured) {
27        NSMethodSignature *signature = [anInvocation methodSignature];
28        const char *objCType = [signature messageArgumentTypeAtIndex:_argumentIndex];
29        if (KWObjCTypeIsObject(objCType)) {
30            id argument = nil;
31            [anInvocation getMessageArgument:&argument atIndex:_argumentIndex];
32            if (KWObjCTypeIsBlock(objCType)) {
33                _argument = [argument copy];
34            } else {
35                _argument = [argument retain];
36            }
37        } else {
38            NSData *data = [anInvocation messageArgumentDataAtIndex:_argumentIndex];
39            _argument = [[KWValue valueWithBytes:[data bytes] objCType:objCType] retain];
40        }
41        _argumentCaptured = YES;
42    }
43}
44
45- (void)dealloc {
46    [_argument release];
47    [super dealloc];
48}
49@end