Ho 在混合应用程序(主要语言 ObjC)中从 Swift 获取对 appdelegate 的引用,以避免引用循环



首先,我知道的是:如何在 Swift 中获取对应用程序委托的引用?

其次,我需要做的是访问混合应用的 Swift 端的 appdelegate 属性。

基本上
1-我有一个项目,该项目是作为目标C项目开始的。这意味着 AppDelegate 是在目标 C 端定义的。
2-我有快速代码工作正常,我有一个桥头,我可以引用另一侧任何一侧的东西。
3-问题是:要在我的 Swift 代码中引用 appdelegate,我需要在我的桥接标头中#import "AppDelegate.h"。但由于其他原因,我还需要 AppDelegate.h 来导入 SWift 标头 ( PROJECT-Swift.h )。这将创建一个引用循环。

有没有办法避免这种引用循环? 并且仍然访问 AppDelegate 属性?

编辑:我在问题的第一版中没有提到的另一个复杂问题是,我想向 Swift 代码公开的 AppDelegate 属性实际上是在 Swift 端声明的类型。所以我需要在AppDelegate.h中声明它,为了能够做到这一点,我需要在我的AppDelegate.h中导入-Swift.h标头。
为了更清楚:
KB是在 Swift 端定义的public class
AppDelegate 具有如下属性:@property (strong) KB *appkb; 我需要掌握((AppDelegate*)UIApplication.SharedApplication()).appkb

你应该在AppDelegate.m中导入PROJECT-Swift.h,而不是.h

AppDelegate.h中,你可以使用"前向声明"(@class@protocol),如下所示:

AppDelegate.h:

#import <UIKit/UIKit.h>
@class SwiftClass;
@class KB;
@protocol SwiftProtocol;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) id<SwiftProtocol> swifter;
@property (strong, nonatomic) KB *appkb;
-(void)methodReceiveSwiftClass:(SwiftClass *)obj;
//...
@end

AppDelegate.m:

#import "AppDelegate.h"
#import "PROJECT-Swift.h"
@implemetation AppDelegate
//....
@end

PROJECT-Bridging-Header.h

#import "AppDelegate.h"

任何.swift:

@objc public protocol SwiftProtocol {
    // ...
}
@objc public class SwiftClass:NSObject {
    // ...
}
@objc public class KB:NSObject {
    // ...
}

该文件说:

为了避免循环引用,不要将 Swift 导入到 Objective-C 头文件中。相反,你可以转发声明一个 Swift 类,以便在 Objective-C 标头中使用它。请注意,您不能在 Objective-C 中对 Swift 类进行子类化。

最新更新