Ho to get AppDelegate reference from Swift in mixed use (ObjC core language) to avoid reference path

First of all, I am aware of this: How do I get the app delegate reference in Swift?

Second, I need to access the appdelegate properties on the Swift side of the mixed app.

Basically,
I have a project that runs as an Objective C project. This means the AppDelegate is defined on the Objective C side.

2- I have a quick code working fine, I have a bridge header and I can reference things from both sides on the other side.
3- Here is the problem: To reference the appdelegate in my Swift code I need #import "AppDelegate.h"

in my bridge header. But for other reasons I also need AppDelegate.h to import the SWift ( PROJECT-Swift.h

) header . This creates a reference cycle.

Is there a way to avoid this link cycle? and still accessing AppDelegate properties?

EDIT: An additional complication that I didn't mention in the first issue of the question is that the AppDelegate property I want to expose to Swift code is actually of a type declared on the Swift side. So I need to declare it in AppDelegate.h

and in order to do that I need to import the header -Swift.h

into mine AppDelegate.h

.
To make it clearer:
KB

is public class

, defined on the Swift side.
AppDelegate has a property like: @property (strong) KB *appkb;

I need to get((AppDelegate*)UIApplication.SharedApplication()).appkb

+3


source to share


1 answer


You should import PROJECT-Swift.h

to AppDelegate.m

, not.h

As AppDelegate.h

you can use the "forward declaration" ( @class

and @protocol

), for example:

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

      



Design-bridge-header.h

#import "AppDelegate.h"

      

Any.swift:

@objc public protocol SwiftProtocol {
    // ...
}

@objc public class SwiftClass:NSObject {
    // ...
}

@objc public class KB:NSObject {
    // ...
}

      

The doc says:

To avoid circular references, do not import Swift into an Objective-C header file. Instead, you can redirect the Swift class declaration to use it in the Objective-C header. Please note that you cannot subclass Swift class in Objective-C.

+6


source







All Articles