objective-c - NSProxy "transform itself into another object"怎么办?

标签 objective-c cocoa cocoa-touch nsproxy

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/

相关文章:

objective-c - 从 iPhone 上的 PNG 图像读取像素颜色值的简单方法?

objective-c - 如何以编程方式确定 OS X 上 Retina MacBook Pro 屏幕的原始像素分辨率?

iphone - 使用 Core Data 有哪些优点? (相对于 plist)

ios - UIButton 为状态正常设置图像,在不同状态下隐藏该图像

ios - 子类化 UIView。 init 方法永远不会被调用

objective-c - 当用户在 NSAlert 后按 Enter 时未设置 NSIndexSet

Objective-C:将两个整数相除并返回一个四舍五入的整数值

ios - 为什么我在 Objective-C 中的枚举上收到类型冲突警告?

objective-c - 检查 NSMutableArray 上是否有重复的 NSString

objective-c - 如何向字符串添加度数符号?