Swift与OC混编之协议的使用

Swift与OC混编之协议的使用,第1张

一 OC使用Swift的协议

swift代码:

@objc protocol TestProtocol{
    
    func testMethod()->Void
}

@objc class UseProtocol:NSObject{
    
    @objc weak var delegate:TestProtocol?
    @objc func takeSwiftProtocol(){
        self.delegate?.testMethod()
    }
}

OC代码:


#import 

NS_ASSUME_NONNULL_BEGIN

@interface OCUseSwiftProtocol : NSObject


-(void)takeSwiftDelegate;

@end

NS_ASSUME_NONNULL_END
#import "OCUseSwiftProtocol.h"
#import "OCBaseProject-Swift.h"

@interface OCUseSwiftProtocol()

@property(nonatomic, strong)UseProtocol * up;

@end

@implementation OCUseSwiftProtocol

-(void)takeSwiftDelegate
{
    _up = [[UseProtocol alloc] init];
    self.up.delegate = self;
    [self.up takeSwiftProtocol];
}

//实现swift中类的协议方法
-(void)testMethod
{
    NSLog(@"Swift类UseProtocol的实例变量,调用代理self实现的协议方法成功");
}


@end

二  Swift使用OC的协议

OC代码:

//
//  OCTestProtocol.h
//  OCBaseProject
//
//  Created by Alisa on 2022/4/25.
//

#ifndef OCTestProtocol_h
#define OCTestProtocol_h

#import 

@protocol OCTestProtocol 

-(void)ocTestProtoclMethod;

@end


#endif /* OCTestProtocol_h */
//
//  SwiftUseOcProtocol.h
//  OCBaseProject
//
//  Created by Alisa on 2022/4/25.
//

#import 
#import "OCTestProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface SwiftUseOcProtocol : NSObject

@property(nonatomic, weak)iddelegate;

-(void)takeMethod;

@end

NS_ASSUME_NONNULL_END
//
//  SwiftUseOcProtocol.m
//  OCBaseProject
//
//  Created by Alisa on 2022/4/25.
//

#import "SwiftUseOcProtocol.h"

@interface SwiftUseOcProtocol()
@end

@implementation SwiftUseOcProtocol

-(void)takeMethod
{
    [self.delegate ocTestProtoclMethod];
}



@end

Swift代码:

//
//  ProtocolSwift.swift
//  OCBaseProject
//
//  Created by Alisa on 2022/4/25.
//

import Foundation

@objc class UseOCProtocol:NSObject,OCTestProtocol{
    
    @objc func takeOcProtocol(){
        
        let sop:SwiftUseOcProtocol = SwiftUseOcProtocol()
        sop.delegate = self
        sop.takeMethod()
    }
    
    func ocTestProtoclMethod() {
        print("OC类SwiftUseOcProtocol实例变量,delegate成功调用代理者实现的方法。")
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993086.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存