Development Tip

Objective C 클래스에서 Swift 함수 호출

yourdevel 2020. 11. 1. 18:48
반응형

Objective C 클래스에서 Swift 함수 호출


문제가 있습니다. 이전 Objective C 프로젝트가 있고 새 Swift 함수와 객체를 호출하고 싶습니다. "-Bridging-Header.h"및 "-Swift.h"파일을 만들었습니다.

Swift에서 Objective C로 함수를 호출하기는 쉽지만 반대로 문제가 있습니다.

그래서 "System.Swift"라는 간단한 클래스를 만들었습니다.

import Foundation

@objc class System : NSObject {

@objc func printSome() {
    println("Print line System");
    }
}

이제 여기 와 <...>-Swift.h 파일 내부의 문서를 따르려고 노력 했습니다.

@class System;

@interface System : NSObject

-(void)printSome;

@end

내 Objective C 클래스 내에서 가져 왔습니다. 이 시점에서 내 Objective C 코드의 Objective C 클래스 (현재 UIViewController) 내에서 "printSome"메서드를 호출하려고합니다.

- (void)viewDidLoad
{
    [super viewDidLoad];
    System * sis = [[System alloc] init];
    [sis printSome];
    //any additional setup after loading the view from its nib.
}

이제 다음 오류가 있습니다.

아키텍처 i386에 대한 정의되지 않은 기호 : "_OBJC_CLASS _ $ _ System", 참조 : "ObjectiveC_Class_That_Call_Swift_Object"의 objc-class-ref : 아키텍처 i386에 대한 기호를 찾을 수 없음 clang : 오류 : 링커 명령이 종료 코드 1로 실패했습니다 (사용 -v 호출 참조)

누군가 나를 도울 수 있습니까?

모두 감사합니다.


문제가 해결되었습니다. 이전에 Objective-C 클래스 .h파일을 만들고 포함 시켰지만 나중에 발견 했듯이 컴파일러가 필요한 파일을 보이지 않게 만들기 때문에이 단계가 필요하지 않습니다.<ProductModuleName>-Swift.h

<ProductModuleName>-Swift.h수업에 포함 하기 만하면 작동합니다.


네 감사합니다

이상하지만 작동합니다

1) Add @objc  to  Swift class

2) Add in .m 
    #import "(ProjectName)-Swift.h"

3) Call from .h
    @class SwiftClass;

4)On SwiftClass 
   click "Command" + Left Click (Apple Documantation)

5) To see "-Swift.h" -> click "Command" + Left Click

앱은 -Swift.h에서이 클래스에 대한 인터페이스를 생성합니다.

예 : SWIFT_CLASS ( "_ TtC10Project17220PLHelper") @interface PLHelper

  • (void)notifyForDownloading:(NSDictionary *)userInfo;
  • (instancetype)init OBJC_DESIGNATED_INITIALIZER; @end

Assume We have ProjectName "MyFirstProjectOnSwift" and swift class name "mySwiftClass" and objectiveC class is "MyObjectiveCLass"

Following steps are:-

  1. Add #import "MyFirstProjectOnSwift-Swift.h" in "MyObjectiveCLass.m"

  2. Add @class mySwiftClass in MyObjectiveCLass.h;

  3. Then in MyObjectiveCLass.m

    mySwiftClass *myClass = [mySwiftClass new]; {Call Like This in any method wherever you want to call swift method.}

  4. [myClass methodName];


Check the -Swift.h file which has the import on your .m file in objective-C:

#import <YourProjectName-Swift.h>

Click on that line, and left-click - Jump To Definition.

This file should be included automatically, not manually.


If you're still not seeing your class even after importing <ProductModuleName>-Swift.h.

Make sure that your class is subclassing a native class (e.g UIViewController) or at least if it's just a utility class, make it subclass NSObject. Your class should now show.

참고URL : https://stackoverflow.com/questions/24078043/call-swift-function-from-objective-c-class

반응형