原文地址:http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift

Using Objective-C Classes in Swift(在swift中使用oc)

** 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 ObjC File) **

Step 1: Add Objective-C Implementation -- .m(添加.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:(自动弹出桥接文件选项)

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  and reference it from your build settings(如果没有自动弹出,则手动添加桥接文件,命名规则<#YourProjectName#>-Bridging-Header.h,然后在BuildSettings中添加如下配置)

Step 3: Add Objective-C Header -- .h(添加对应.h文件)

Add another .h file and name it CustomObject.h

Step 4: Build your Objective-C Class

In CustomObject.h

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

In CustomObject.m

  1. #import "CustomObject.h"
  2. @implementation CustomObject
  3. - (void) someMethod {
  4. NSLog(@"SomeMethod Ran");
  5. }
  6. @end

Step 5: Add Class to Bridging-Header(将.h文件import到桥接文件)

In YourProject-Bridging-Header.h:

  1. #import "CustomObject.h"

Step 6: Use your Object(在swift工程中就可以直接调用了)

In SomeSwiftFile.swift:

  1. var instanceOfCustomObject: CustomObject = CustomObject()
  2. instanceOfCustomObject.someProperty = "Hello World"
  3. println(instanceOfCustomObject.someProperty)
  4. instanceOfCustomObject.someMethod()

No need to import explicitly, that's what the bridging header is for.

Using Swift Classes in Objective-C(在oc中使用swift)

Step 1: Create New Swift Class

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

In MySwiftObject.swift:

  1. import Foundation
  2. class MySwiftObject : NSObject {
  3. var someProperty: AnyObject = "Some Initializer Val"
  4. init() {}
  5. func someFunction(someArg:AnyObject) -> String {
  6. var returnVal = "You sent me \(someArg)"
  7. return returnVal
  8. }
  9. }

Step 2: Import Swift Files to ObjC Class

In SomeRandomClass.m:

  1. #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

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

Using PURE Swift Classes in Objective-C

As pointed out by @TomášLinhart in the comments, "To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc." Because our first example is a descendant of NSObject, the compiler does this automatically. Let's look at an example class that is not a descendant of an Objective-C Class.

Step 1: Create New Swift Class

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

In PureSwiftObject.swift:

  1. import Foundation
  2. // Note '@objc' prefix
  3. @objc class PureSwiftObject {
  4. var name: String
  5. init(name: String) {
  6. self.name = name
  7. }
  8. // Needed to add a class level initializer
  9. class func newInstanceNamed(name: String) -> PureSwiftObject {
  10. return PureSwiftObject(name: name)
  11. }
  12. // Just a method for demonstration
  13. func someMethod() {
  14. println("Some method ran in pure swift object")
  15. }
  16. }

For this, I create a class initializer called 'newInstanceNamed:'. Because this class is no longer a descendent of NSObject, it no longer has access to 'alloc' or 'new'. Perhaps there is another workaround, but this is the only way that I have found. I didn't find any explicit mention of this in the docs. If you do, and it contradicts my approach, please tell me and I'll update the answer to conform to the suggested style.

Step 2: Import Swift Files to ObjC Class

In SomeRandomClass.m:

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

(if you haven't already done so)

Step 3: Use your pure swift class

  1. PureSwiftObject * pureSwiftObject = [PureSwiftObject newInstanceNamed:@"Janet"];
  2. NSLog(@"PureSwiftNamed: %@", pureSwiftObject.name);
  3. [pureSwiftObject someMethod];

Note:

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

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

Swift实战(2)--在工程中添加object-C的类或者第三方框架(附翻译)的更多相关文章

  1. ARC工程中添加非ARC文件

    转载自:http://blog.csdn.net/zhenweicao/article/details/16988543 分类: IOS2013-11-27 17:02 626人阅读 评论(0) 收藏 ...

  2. 工程中添加工程依赖 Xcode iOS

    有时我们需要在一个主工程中添加其他的子工程,用来对子工程进行编写修改或者是利用子工程中的库文件等等操作,这时候我们需要用到工程的嵌套.   步骤:(看图说话)   1.新建主工程,名为TestTTTT ...

  3. IOS学习:在工程中添加百度地图SDK

    1.将下载下来的sdk中的inc文件夹.mapapi.bundle.libbaidumapapi.a添加到工程中,其中libbaiduapi.a有两个,一个对应模拟器一个对应真机,导入方法如下: 第一 ...

  4. 关于在工程中添加新文件时的LNK2019错误的一个解决办法

    我这几天一直在研究Qt的串口程序,在读懂了官方给出的实例程序后我决定把其多线程的串口监视程序加入到我自己的工程中,便直接把问价复制到自己的工程下面,在Qt中加入到自己的工程中,但是总是出现LNK201 ...

  5. step6----->往工程中添加spring boot项目------->修改pom.xml使得我的project是基于spring boot的,而非直接基于spring framework

    文章内容概述: spring项目组其实有多个projects,如spring IO platform用于管理external dependencies的版本,通过定义BOM(bill of mater ...

  6. 在工程中添加pch文件

    在Xcode6之前,新建一个工程的时候,系统会帮我们自动新建一个以工程名为名字的pch (precompile header)文件,在开发过程中,可以将那些整个工程都广泛使用的头文件包含在该文件下,编 ...

  7. WPF - 为什么不能往Library的工程中添加WPF window

    项目中添加一个Library 工程,但是却无法加入WPF window, WPF customize control. 调查了一下,发现这一切都由于Library工程中没有:ProjectTypeGu ...

  8. VS工程中添加c/c++工程中外部头文件及库的基本步骤

    转载自 在VS工程中,添加c/c++工程中外部头文件及库的基本步骤: 1.添加工程的头文件目录:工程---属性---配置属性---c/c++---常规---附加包含目录:加上头文件存放目录. 2.添加 ...

  9. Visual Studio 向工程中添加文件夹

    将要添加的文件夹拷贝到工程的目标文件夹中. 打开工程,在Solution Explorer中选中“Show All Files”按钮. 然后VS会显示文件夹中包含,但是不在工程中的文件夹. 右键该文件 ...

随机推荐

  1. 12、NIO、AIO、BIO一

    1.NIO概述 什么是NIO:NIO是New I/O的简称,与旧式的基于流的I/O方式相对,从名字看,他表示新的一套JAVA I/O标准.它是在java1.4中被纳入到JDK中的,并具有以下特性: - ...

  2. uva_11997,K Smallest Sums优先队列

    #include<iostream> #include<cstdio> #include<cstring> #include<queue> #inclu ...

  3. thinkphp5项目--个人博客(六)

    thinkphp5项目--个人博客(六) 项目地址 fry404006308/personalBlog: personalBloghttps://github.com/fry404006308/per ...

  4. BZOJ 3680 模拟退火

    思路: 退火就好了-- 1.强烈建议题目名称改为"吊打出题人" 2.这种题放oj上啥心态...-–hzwer 二分TLE和WA 终于AC了-- //By SiriusRen #in ...

  5. Python有了asyncio和aiohttp在爬虫这类型IO任务中多线程/多进程还有存在的必要吗?

    最近正在学习Python中的异步编程,看了一些博客后做了一些小测验:对比asyncio+aiohttp的爬虫和asyncio+aiohttp+concurrent.futures(线程池/进程池)在效 ...

  6. <Sicily>Fibonacci 2

    一.题目描述 In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn-1 + Fn-2 for n ≥ 2. For exampl ...

  7. SQL--去除字符串空格、截取字符串

  8. laravel模板机制

    @extends('layouts.master') @section('title', 'Page Title') @section('sidebar') @parent <p>This ...

  9. Kubernetes本地私有仓库配置

    实验环境 master 10.6.191.181 node1 10.6.191.182 node2 10.6.191.183 本地私有仓库 10.6.191.184 一.安装本地私有仓库 1.安装do ...

  10. 基于Linux的智能家居的设计(2)

    1  系统整体设计方案 智能家居系统的是一个实时查询家庭的温湿度.照明控制.自己主动控制的设定.集家庭娱乐.智能安防为一体,大量数据快处理.可靠的系统,因此在硬件和软件上都有非常大的要求,因此在这里进 ...