问题描述
说:
将自身转换为真实对象是如何工作的?
How exactly would the "transform itself into the real object" work?
为了使事情更具体,假设 Foo
有一个方法 newFooWithString:
,它接受一个字符串并返回 Foo
的新实例。是否可以设置一个 NSProxy
,如果收到 pleaseBecomeAFooUsingString:@bar
,将自身转换为 [Foo newFooWithString:@bar]
,占用相同的内存,而不会混淆其他可能存在的引用?
To make things a little more specific, suppose class Foo
has a method newFooWithString:
that takes a string and returns a new instance of Foo
. Would it be possible to setup an NSProxy
that sits around, and if a pleaseBecomeAFooUsingString: @"bar"
message is received, transforms itself into [Foo newFooWithString: @"bar"]
, occupying the same memory, without messing with other references to itself that may exist?
推荐答案
如果你有一个指向同一NSProxy实例的代码,并将转换它,它将改变所有的代码。没有办法区分对象的方法的调用者,因此您将无法自动替换目标来转发代码中的方法调用。常见的可变形代理将采用以下方式:
If you have a pointer to the same NSProxy instance all over the code and will "transform" it, it will change all over the code. There is no way to differentiate a caller of a method for an object, so you will not be able to alternate targets for forwarding of methods invocation in your code automatically. Common transformable proxy will looks in following way:
#import <Foundation/Foundation.h>
@interface MyTrickyProxy : NSProxy {
NSObject *object;
}
- (id)transformToObject:(NSObject *)anObject;
@end
#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是一个消息的简单转发器,没有任何魔法,所以你的目标是不能实现的方式,如你所述。
So what you requested is some sort of code-magic, but NSProxy is a simple forwarder of a messages, there is no any magic at all, so your goal is not achievable in a way as you described.
这篇关于NSProxy如何“将自身转换成另一个对象”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!