Swift class using Objective-C class using Swift class

前端 未结 1 1913
醉酒成梦
醉酒成梦 2021-01-05 10:13

I have an obj-c project to which I successfully added a new Swift class A, which is being used by some existing obj-c class B - the use of the automatically generated \"MyPr

相关标签:
1条回答
  • 2021-01-05 10:39

    This is a typical cyclical referencing problem.

    Be careful to read the docs:

    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.

    So, you should use "forward declare" in .h, and #import in .m:

    //  ObjCClass.h
    #import <Foundation/Foundation.h>
    
    @class SwiftClassA;
    
    @interface ObjCClass : NSObject
    @property (nonatomic, strong) SwiftClassA *aProperty;
    @property (nonatomic) int *aNumber;
    @end
    
    // ObjCClass.m
    #import "ObjCClass.h"
    #import "MyProject-Swift.h"
    
    @implementation ObjCClass
    // your code
    @end
    
    0 讨论(0)
提交回复
热议问题