如果您在整个代码中都有一个指向同一个 NSProxy 实例的指针并且将“转换”它,那么它将在整个代码中发生变化。无法区分对象的方法调用者,因此您将无法在代码中自动替换目标以转发方法调用。常见的可转换代理将如下所示:
MyTrickyProxy.h
#import <Foundation/Foundation.h>
@interface MyTrickyProxy : NSProxy {
NSObject *object;
}
- (id)transformToObject:(NSObject *)anObject;
@end
MyTrickyProxy.m
#import "MyTrickyProxy.h"
@implementation MyTrickyProxy
- (void)dealloc
{
[object release];
object = nil;
[super dealloc];
}
- (NSString *)description
{
return [object description];
}
//Stupid transform implementation just by assigning a passed in object as transformation target. You can write your factory here and use passed in object as id for object that need ot be created.
- (id)transformToObject:(NSObject *)anObject
{
if(object != anObject) {
[object release];
}
object = [anObject retain];
return object;
}
- (void)forwardInvocation:(NSInvocation *)invocation
{
if (object != nil) {
[invocation setTarget:object];
[invocation invoke];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
NSMethodSignature *result;
if (object != nil) {
result = [object methodSignatureForSelector:sel];
} else {
//Will throw an exception as default implementation
result = [super methodSignatureForSelector:sel];
}
return result;
}
@end
所以你要求的是某种代码魔法,但是 NSProxy 是一个简单的消息转发器,根本没有任何魔法,所以你的目标无法以你描述的方式实现。