NSProxy是消息转发的抽象父类,可以利用NSInvocation进行消息转发。
@class NSMethodSignature, NSInvocation;
NS_ROOT_CLASS
@interface NSProxy <NSObject> {
Class isa;
}
+ (id)alloc;
+ (id)allocWithZone:(NSZone *)zone NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
+ (Class)class;
- (void)forwardInvocation:(NSInvocation *)invocation;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel;
- (void)dealloc;
- (void)finalize;
@property (readonly, copy) NSString *description;
@property (readonly, copy) NSString *debugDescription;
+ (BOOL)respondsToSelector:(SEL)aSelector;
- (BOOL)allowsWeakReference NS_UNAVAILABLE;
- (BOOL)retainWeakReference NS_UNAVAILABLE;
// - (id)forwardingTargetForSelector:(SEL)aSelector;
@end
可以看出,
NSProxy和NSObject一样,也是根类哦。
@interface Man : NSProxy
- (void)makeSomeAirplane:(NSString *)airPlaine; //造飞机
@end<pre name="code" class="objc">@implementation Man
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
NSMethodSignature *sig = [RichFriend instanceMethodSignatureForSelector:aSelector];
if (!sig) {
if ([RichFriend instancesRespondToSelector:aSelector]) {
sig = [RichFriend instanceMethodSignatureForSelector:aSelector];
}
}
return sig;
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
if ([RichFriend instancesRespondToSelector:anInvocation.selector]) {
[anInvocation invokeWithTarget:RichFriend.new];
} else {
[super forwardInvocation:anInvocation];
}
}
@end
@interface RichFriend : NSObject
@end
@implementation RichFriend
- (void)makeSomeAirplane:(NSString *)airPlaine
{
NSLog(@"%@",[NSString stringWithFormat:@"制造%@成功",airPlaine]);
}
@end
可以
看出和普通的类的消息完全一样,NSProxy如果没有相应的方法,就会进行消息转发。