gpt4 book ai didi

objective-c - 在 objective c 类中使用委托(delegate)调用 swift 方法

转载 作者:行者123 更新时间:2023-11-28 15:38:01 27 4
gpt4 key购买 nike

我有两个文件

问题.m
问题.h

这两个都是Objective-C写的

MainView.swift

这是 Swift 写的

问题类有代表

@interface Question : NSObject{

id delegate;// put MainViewController here

- (void)trythisfunction{
[delegate test] // compiler doesn't find this method.
}
}

然后我创建类实例并将 MainViewController 作为 MainViewController.swift 中问题的委托(delegate)

 class MainViewController: UIViewController {
override func viewDidLoad(){
q = Question()
q.delegate = self // put self in delegate
}
func test(){
NSLog("test is OK")
}
}

但是编译器发现错误[委托(delegate)测试]Question.m:169:19:选择器“test:”没有已知的实例方法

我该如何解决这个问题??

最佳答案

您需要做一些更改。

下面的类声明无法编译,因为您不能在 interface 中声明变量。

    @interface Question : NSObject{

id delegate;

- (void)trythisfunction {
[delegate test]
}
}

我已经修复了上面的问题,类现在看起来像这样,

 # Question.h file
#import <Foundation/Foundation.h>

@interface Question : NSObject
@property (nonatomic, strong) id delegate;
@end

下面是类的实现

 # Question.m file
#import "Question.h"

@implementation Question

@synthesize delegate;

- (void)trythisfunction{
[delegate test];
}
@end

因为我们正在集成这个 swift,所以我们需要一个 Bridging Header其内容看起来像。

  #import "Test.h"

现在终于可以在你的 swift 类中导入这个类了

import UIKit

class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let q = Test()
q.delegate = self
}
func test(){
NSLog("test is OK")
}
}

上面的代码很有魅力。

关于objective-c - 在 objective c 类中使用委托(delegate)调用 swift 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44084702/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com