一 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 <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface OCUseSwiftProtocol : NSObject
-(void)takeSwiftDelegate;
@end
NS_ASSUME_NONNULL_END
#import "OCUseSwiftProtocol.h"
#import "OCBaseProject-Swift.h"
@interface OCUseSwiftProtocol()<TestProtocol>
@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 <Foundation/Foundation.h>
@protocol OCTestProtocol <NSObject>
-(void)ocTestProtoclMethod;
@end
#endif /* OCTestProtocol_h */
//
// SwiftUseOcProtocol.h
// OCBaseProject
//
// Created by Alisa on 2022/4/25.
//
#import <Foundation/Foundation.h>
#import "OCTestProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface SwiftUseOcProtocol : NSObject
@property(nonatomic, weak)id<OCTestProtocol>delegate;
-(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成功调用代理者实现的方法。")
}
}
|