// MyProxy.h
#import
<Foundation/Foundation.h>
@interface MyProxy :
NSProxy {
NSObject *object;
}
- (id)transformToObject:(NSObject *)anObject;
@end
// MyProxy.m
#import
"MyProxy.h"
@implementation MyProxy
- (void)dealloc
{
[object
release];
object = nil;
[super
dealloc];
}
- (void)fun
{
// Do someting virtual
//
先做一些代理工作,然後建立一個後台線程,在後台線程中再調用真正的[object fun];
}
// 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
// RealSubject.h
#import
<Foundation/Foundation.h>
@implementation RealSubject : NSObject
- (void)fun;
@end
// RealSubject.m
#import
"RealSubject.h"
@implementation RealSubject
- (void)fun
{
//
這個方法需要代理進行惰性調用
// Do something real
}
- (void)otherFun
{
//
這個方法不需要代理做任何處理,可直接被調用
// Do something real
}
@end
// main.m
int main(int argc,
char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool
alloc]
init];
MyProxy *myProxy = [MyProxy
alloc];
RealSubject *realSub = [[RealSubject
alloc] init];
[myProxy
transformToObject:realSub];
[myProxy
fun];
// 直接調用myProxy的fun,執行代理工作
[myProxy
otherFun];
// 依次調用myProxy的methodSignatureForSelector和forwardInvocation轉寄給realSub,realSub調用otherFun
[realSubject
release];
[myProxy
release];
[pool
release];
return 0;
}
注意,調用MyProxy中未定義的方法otherFun會出現'MyProxy' may not respond to 'fun'的警告,可通過使用私人範疇或通過performSelector:withObject:來避免,如果有更好的方法,請告知。