NSProxy Class Reference是这样说的:
Typically, a message to a proxy is forwarded to the real object or causes the proxy to load (or transform itself into) the real object.
“将自身转化为真实对象”究竟是如何工作的?
为了让事情更具体一点,假设类 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 是一个简单的消息转发器,根本没有任何魔法,所以你的目标无法按照你描述的方式实现。
关于objective-c - NSProxy "transform itself into another object"怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970220/