I need to create proxy pattern in iOS using swift
I have tried it using Objective C and here is the code
MyProtocol.h
#import <Foundation/Foundation.h>
@protocol MyProtocol <NSObject>
@required
-(void)testMessage;
@end
TestBO.h
#import <Foundation/Foundation.h>
#import "MyProtocol.h"
@interface TestBO : NSObject <MyProtocol>
@end
TestBO.m
#import "TestBO.h"
@implementation TestBO
-(void)testMessage{
NSLog(@"Test Message");
}
@end
TestProxyHandler.h
#import <Foundation/Foundation.h>
@interface TestProxyHandler : NSProxy
@property (nonatomic, strong) id object;
- (instancetype)initWithProtocol:(Protocol *)protocol andObject:(Class)clazz;
- (void)forwardInvocation:(NSInvocation *)invocation;
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector;
@end
TestProxyHandler.m
#import "TestProxyHandler.h"
#import "TestBO.h"
@implementation TestProxyHandler
- (instancetype)initWithProtocol:(Protocol *)protocol andObject:(Class)clazz{
if ([clazz conformsToProtocol:@protocol(MyProtocol)]) {
self.object = [[clazz alloc] init];
}else{
NSLog(@"Error it does not conform to protocol");
}
return self;
}
- (void)forwardInvocation:(NSInvocation *)invocation{
NSString *selString = NSStringFromSelector(invocation.selector);
NSLog(@"Called %@",selString);
[invocation invokeWithTarget:self.object];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
return [self.object methodSignatureForSelector:selector];
}
@end
I have invoked it using
id <MyProtocol> delegate = (TestBO *)[[TestProxyHandler alloc] initWithProtocol:@protocol(MyProtocol) andObject:[TestBO class]];
[delegate testMessage];
But I am not able to make it work in Swift even the initialzier is showing that the message
TestHandler.swift
import Foundation
class TestHandler: NSProxy {
var object: AnyObject
convenience override init(`protocol`: Protocol, andObject clazz: AnyClass) {
if clazz.conformsToProtocol() {
self.object = clazz()
}
else {
NSLog("Error it does not conform to protocol")
}
}
}
Does anyone have any clue to do this in swift ??
EDIT:
In java you can create runtime implementation of a method using the Proxy.newProxyInstance call but can this be achieved in iOS ? using swift ? Any clue ?