我需要使用 swift 在 iOS 中创建代理模式
我已经使用Objective C尝试过,这里是代码
我的协议.h
#import <Foundation/Foundation.h>
@protocol MyProtocol <NSObject>
@required
-(void)testMessage;
@end
测试BO.h
#import <Foundation/Foundation.h>
#import "MyProtocol.h"
@interface TestBO : NSObject <MyProtocol>
@end
测试BO.m
#import "TestBO.h"
@implementation TestBO
-(void)testMessage{
NSLog(@"Test Message");
}
@end
测试代理处理程序.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
测试代理处理程序.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
我已经调用它使用
id <MyProtocol> delegate = (TestBO *)[[TestProxyHandler alloc] initWithProtocol:@protocol(MyProtocol) andObject:[TestBO class]];
[delegate testMessage];
但我无法让它在 Swift 中工作,即使初始化程序显示消息
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 中实现吗?使用迅速?有什么线索吗?