喵-见缝插针 2014-06-02 20:05 采纳率: 0%
浏览 337
已采纳

如何从 Swift 调用 Objective-C 代码

In the new Swift language from Apple, how does one call Objective-C code?

Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?

The Reasoning

Objective-C is a platform-independent language, whereas Swift is platform-dependent. Writing non-platform-dependent code (business logic libraries) in Swift would thus not be wise. However, writing platform-dependent code in it (interface related for example) would be perfectly fine. Not to say it would be a good idea, however it is definitely an interest.

转载于:https://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift

  • 写回答

15条回答 默认 最新

  • Lotus@ 2014-06-03 00:12
    关注

    Using Objective-C Classes in Swift

    ** If you have an existing class that you'd like to use, perform Step 2 and then skip to Step 5. (For some cases, I had to add an explicit #import <Foundation/Foundation.h to an older Objective-C File.) **

    Step 1: Add Objective-C Implementation -- .m

    Add a .m file to your class, and name it CustomObject.m.

    Step 2: Add Bridging Header

    When adding your .m file, you'll likely be hit with a prompt that looks like this:

    Enter image description here

    Click YES !

    If you did not see the prompt, or accidentally deleted your bridging header, add a new .h file to your project and name it <#YourProjectName#>-Bridging-Header.h.

    In some situations, particularly when working with Objective-C frameworks, you don't add an Objective-C class explicitly and Xcode can't find the linker. In this case, create your .h file named as mentioned above, then make sure you link its path in your target's project settings like so:

    Enter image description here

    Note

    It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(SRCROOT) can be thought of as the directory that contains your .xcodeproj file. It might look like this:

    $(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h
    

    Step 3: Add Objective-C Header -- .h

    Add another .h file and name it CustomObject.h.

    Step 4: Build your Objective-C Class

    In CustomObject.h

    #import <Foundation/Foundation.h>
    
    @interface CustomObject : NSObject
    
    @property (strong, nonatomic) id someProperty;
    
    - (void) someMethod;
    
    @end
    

    In CustomObject.m

    #import "CustomObject.h"
    
    @implementation CustomObject 
    
    - (void) someMethod {
        NSLog(@"SomeMethod Ran");
    }
    
    @end
    

    Step 5: Add Class to Bridging-Header

    In YourProject-Bridging-Header.h:

    #import "CustomObject.h"
    

    Step 6: Use your Object

    In SomeSwiftFile.swift:

    var instanceOfCustomObject: CustomObject = CustomObject()
    instanceOfCustomObject.someProperty = "Hello World"
    println(instanceOfCustomObject.someProperty)
    instanceOfCustomObject.someMethod()
    

    There is no need to import explicitly; that's what the bridging header is for.

    Using Swift Classes in Objective-C

    Step 1: Create New Swift Class

    Add a .swift file to your project, and name it MySwiftObject.swift.

    In MySwiftObject.swift:

    import Foundation
    
    class MySwiftObject : NSObject {
    
        var someProperty: AnyObject = "Some Initializer Val"
    
        init() {}
    
        func someFunction(someArg:AnyObject) -> String {
            var returnVal = "You sent me \(someArg)"
            return returnVal
        }   
    }
    

    Step 2: Import Swift Files to ObjC Class

    In SomeRandomClass.m:

    #import "<#YourProjectName#>-Swift.h"
    

    The file:<#YourProjectName#>-Swift.h should already be created automatically in your project, even if you can not see it.

    Step 3: Use your class

    MySwiftObject * myOb = [MySwiftObject new];
    NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
    myOb.someProperty = @"Hello World";
    NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
    NSString * retString = [myOb someFunction:@"Arg"];
    NSLog(@"RetString: %@", retString);
    

    Note:

    1. CodeCompletion wasn't behaving as accurately as I'd like it to. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa.

    2. If you add a .swift file to an older project and get error: dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib, try completely restarting Xcode.

    3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行