gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:21:27 26 4
gpt4 key购买 nike

首先我知道这个:How do I get a reference to the app delegate in Swift?

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

基本上,
1- 我有一个作为 Objective C 项目启动的项目。这意味着 AppDelegate 是在 Objective C 端定义的。
2- 我的 swift 代码工作正常,我有一个桥头,我可以从另一边的任何一边引用东西。
3- 这是问题所在:要在我的 Swift 代码中引用 appdelegate,我需要在我的桥接 header 中添加 #import "AppDelegate.h"。但出于其他原因,我还需要 AppDelegate.h 来导入 SWift header ( PROJECT-Swift.h )。这会创建一个引用循环。

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

编辑:我在问题的第一版中没有提到的另一个复杂问题是,我想向 Swift 代码公开的 AppDelegate 属性实际上是在 Swift 端声明的类型。所以我需要在 AppDelegate.h 中声明它,为了能够做到这一点,我需要在我的 AppDelegate 中导入 -Swift.h header 。 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 {
// ...
}

The document说:

To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift class to use it in an Objective-C header. Note that you cannot subclass a Swift class in Objective-C.

关于objective-c - Ho 在混合应用程序(主要语言 ObjC)中从 Swift 获取对 appdelegate 的引用以避免引用循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26911042/

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