NSProxy Class Reference这样说:
“将自身转换为真实对象”将如何工作?
为了使事情更加具体,假设类Foo
具有一个newFooWithString:
方法,该方法接受一个字符串并返回Foo
的新实例。是否有可能设置一个坐在附近的NSProxy
,并且如果接收到pleaseBecomeAFooUsingString: @"bar"
消息,则将其自身转换为[Foo newFooWithString: @"bar"]
,并占用相同的内存,而不会与可能存在的对其自身的其他引用造成困惑?
最佳答案
如果您在整个代码中都有指向同一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是消息的简单转发器,根本没有任何魔术,因此您无法以您所描述的方式实现目标。