原文地址: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

#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(将.h文件import到桥接文件)

In YourProject-Bridging-Header.h:

#import "CustomObject.h"

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

In SomeSwiftFile.swift:

var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someProperty = "Hello World"
println(instanceOfCustomObject.someProperty)
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:

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);

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:

import Foundation

// Note '@objc' prefix
@objc class PureSwiftObject { var name: String
init(name: String) {
self.name = name
} // Needed to add a class level initializer
class func newInstanceNamed(name: String) -> PureSwiftObject {
return PureSwiftObject(name: name)
} // Just a method for demonstration
func someMethod() {
println("Some method ran in pure swift object")
}
}

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:

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

(if you haven't already done so)

Step 3: Use your pure swift class

PureSwiftObject * pureSwiftObject = [PureSwiftObject newInstanceNamed:@"Janet"];
NSLog(@"PureSwiftNamed: %@", pureSwiftObject.name);
[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. 第二章 Linux常用命令

    1.命令基础 命令格式:  命令名  [选项] [参数1] [参数2] 命令必须小写,命令正常执行后返回一个0,表示执行成功,如果执行出错,就反悔一个非零值 2.简单的几个命令  who:列出所有正在 ...

  2. new,malloc,GlobalAlloc具体解释

    WINDOWS下最好的方式是用VirtualAlloc分配内存,他不是在堆,也不是栈,而是直接在进程的地址空间中保留一快内存.尽管用起来最不方便. 可是速度快,也最灵活 new,malloc,Glob ...

  3. Android开发之EditText 详解(addTextChangedListener监听用户输入状态)

    为了实现像qq或者微信输入框的效果,当在 EditText输入字符串时发送按钮显示,当输入框字符消除掉时按钮改变.所以这时候我就要用到addTextChangedListener 用它来监听用户输入状 ...

  4. rest_framework-权限-总结完结篇

    #权限#创建一个权限类 在view添加列表 class MyPermission(object): #message 表示权限决绝时返回的数据 message = "必须是SVIP" ...

  5. 数据结构之fhq-treap

    本文内容部分转自某大佬博客:https://blog.csdn.net/CABI_ZGX/article/details/79963427 例题:https://www.luogu.org/probl ...

  6. [学习笔记]node.js中的path.extname方法

    path.extname 返回path路径文件扩展名,如果path以 ‘.' 为结尾,将返回 ‘.',如果无扩展名 又 不以'.'结尾,将返回空值. path.extname('index.html' ...

  7. Python 从入门到精通 全程最佳实现梳理

    零零星星的时间,持续完善中...... 1.一些基础的必要信息归纳 Python 官网 www.python.org 发明者 吉多·范罗苏姆 发行时间 1991年,​26年前 编程泛型 多泛型.面向对 ...

  8. View的双击动作

    有时在android中需要为某一控件设置双击监听,实现也挺简单,自己动手吧.编码永远不是问题,思路才是最重要. public class DoubleClickDemo extends Activit ...

  9. 洛谷P3332 [ZJOI2013]K大数查询 权值线段树套区间线段树_标记永久化

    Code: #include <cstdio> #include <algorithm> #include <string> #include <cstrin ...

  10. 使用commons-email发邮件

    这里我用到了两个包: commons-email-1.3.2.jar mail-1.4.1.jar 如果不加mail.jar,就可能会抛出NoClassDefFoundError异常 之后代码引用ht ...