我需要使用Swift在iOS中创建代理模式
我已经使用Objective C尝试过了,这里是代码
MyProtocol.h
#import@protocol MyProtocol @required -(void)testMessage; @end
测试宝
#import#import "MyProtocol.h" @interface TestBO : NSObject @end
测试版
#import "TestBO.h" @implementation TestBO -(void)testMessage{ NSLog(@"Test Message"); } @end
TestProxyHandler.h
#import@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
我已经使用了它
iddelegate = (TestBO *)[[TestProxyHandler alloc] initWithProtocol:@protocol(MyProtocol) andObject:[TestBO class]]; [delegate testMessage];
但是我无法使它在Swift中工作,即使initialzier显示出该消息
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") } } }
有谁有任何线索迅速做到这一点?
编辑:
在Java中,您可以使用Proxy.newProxyInstance调用创建方法的运行时实现,但是可以在iOS中实现吗?使用swift吗?有什么线索吗?