// 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
//
First do some proxy work, then create a background thread, and then call the real [object fun] In the background thread;
}
// 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
{
//
This method requires a proxy to call the API.
// Do something real
}
-(Void) otherfun
{
//
This method can be called directly without any processing by the proxy.
// Do something real
}
@ End
// Main. m
Int main (INT argc,
Char * argv [])
{
NSAID utoreleasepool * Pool = [[NSAID utoreleasepool
Alloc]
Init];
Myproxy * myproxy = [myproxy
Alloc];
Realsubject * realsub = [[realsubject
Alloc] init];
[Myproxy
Transformtoobject: realsub];
[Myproxy
Fun];
// Directly call myproxy's fun to execute proxy work
[Myproxy
Otherfun];
// Call methodsignatureforselector and forwardinvocation of myproxy in sequence and forward them to realsub. realsub calls otherfun.
[Realsubject
Release];
[Myproxy
Release];
[Pool
Release];
Return 0;
}
Note: When you call an undefined method in myproxy, otherfun will receive a warning that 'myproxy' may not respond to 'fun ', which can be avoided by using a private category or using javasmselector: withobject, please let us know if there is a better method.