ASWeakProxy.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface ASWeakProxy : NSProxy
/**
* @return target The target which will be forwarded all messages sent to the weak proxy.
*/
@property (nonatomic, weak, readonly) id target;
/**
* An object which forwards messages to a target which it weakly references
*
* @discussion This class is useful for breaking retain cycles. You can pass this in place
* of the target to something which creates a strong reference. All messages sent to the
* proxy will be passed onto the target.
*
* @return an instance of ASWeakProxy
*/
+ (instancetype)weakProxyWithTarget:(id)target NS_RETURNS_RETAINED;
@end
ASWeakProxy.mm
1
2
3
4
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return _target;
}
1
2
3
4
- (BOOL)respondsToSelector:(SEL)aSelector
{
return [_target respondsToSelector:aSelector];
}
1
2
3
4
- (BOOL)conformsToProtocol:(Protocol *)aProtocol
{
return [_target conformsToProtocol:aProtocol];
}
1
2
3
4
- (BOOL)isKindOfClass:(Class)aClass
{
return [_target isKindOfClass:aClass];
}
1
2
3
4
5
6
7
8
9
10
11
12
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
ASDisplayNodeAssertNil(_target, @"ASWeakProxy got %@ when its target is still alive, which is unexpected.", NSStringFromSelector(_cmd));
// Unfortunately, in order to get this object to work properly, the use of a method which creates an NSMethodSignature
// from a C string. -methodSignatureForSelector is called when a compiled definition for the selector cannot be found.
// This is the place where we have to create our own dud NSMethodSignature. This is necessary because if this method
// returns nil, a selector not found exception is raised. The string argument to -signatureWithObjCTypes: outlines
// the return type and arguments to the message. To return a dud NSMethodSignature, pretty much any signature will
// suffice. Since the -forwardInvocation call will do nothing if the target does not respond to the selector,
// the dud NSMethodSignature simply gets us around the exception.
return [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
}
1
2
3
4
- (void)forwardInvocation:(NSInvocation *)invocation
{
ASDisplayNodeAssertNil(_target, @"ASWeakProxy got %@ when its target is still alive, which is unexpected.", NSStringFromSelector(_cmd));
}