当前位置:   iOS > 正文

iOS中的代理模式-Swift

nsproxy,ios,swift,swift2,DevBox,在线流程图,编程,编程问答,程序员,开发者工具,开发工具,json解析,二维码生成,unix时间戳,在线开发工具,前端开发工具,开发人员工具,站长工具

我需要使用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

我已经使用了它

id  delegate = (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吗?有什么线索吗?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/iOS/detail/8652
推荐阅读
相关标签
  

闽ICP备14008679号