Swift项目中调用Objective-C的库

这是来自stack overflow上的一个回答,更多回答请查看:

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

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

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:

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 ObjC 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:

Note

It’s best practice to link your project using the (SRCROOT)macrosothatifyoumoveyourproject,orworkonitwithothersusingaremoterepo,itwillstillwork.(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

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

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

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 restarting Xcode.
时间: 2024-08-26 00:48:26

Swift项目中调用Objective-C的库的相关文章

在Android项目中调用已有.so库

注意该.so库指的是android平台的,非一般linux.unix平台:1.现有库libcom_ycan_testLib.so2.新建android项目TestLib23.添加新类:类名:testLib包路径:参考现有库名,应为com.ycan4.在新类中声明库的本地方法,如下: ? 1 2 3 4 5 6 package com.ycan; public class testLib {     public native int add (int a, int b);     public

JNI_Android项目中调用.so动态库

JNI_Android项目中调用.so动态库 2014年6月3日 JNI学习 参考:http://blog.sina.com.cn/s/blog_4298002e01013zk8.html 上一篇笔者介绍了如何使用Java代码调用DLL动态库中的C/C++方法,似乎已经是很久以前的做法了,遇到的错误笔者还未找到解决方案,但动态库着实是找到的,只是无法调用相应的方法.本篇博客来介绍一下如何在Android项目当中使用NDK生成.so动态链接库,并在程序中使用. 1. 在Eclipse中创建项目:T

在 Swift 项目中实现侧滑菜单-利用 SWRevealViewController

你可以完全自己手动写一个侧滑菜单,但是现在在 GitHub 上面已经有很多免费的开源库了,如果不是有很特别的需求,大可不必新建一个轮子. 在这里我使用的这个第三方库名字叫做 SWRevealViewController,作者是 John Lluch.这个免费的类库提供了很方便快捷的方法去把侧滑菜单加入到你的 App 里面,而且它还提供了很多个性化的设置项.它是用 Objective-C 来写的,但是我们也可以很方便的在 Swift 项目中去使用它.你分分钟便可学会如何使用. 首先来看一下我们的

Swift 项目中常用的第三方框架

Swift 项目中可能用到的第三方框架 字数1004 阅读4091 评论17 喜欢93 这里记录下swift开发中可能用的框架 , 最近浏览了不少,积累在这里,以后用的时候方便查阅.顺便推荐给大家! 这里的框架都是纯swift的 , 感谢开源 ,感谢大神们 . 下拉刷新 BreakOutToRefresh 一个下拉刷新打砖块的swift库 SDRefreshView 简单易用的上拉和下拉刷新 ZLSwiftRefresh - 下拉刷新/上拉加载更多,支持自定义动画,集成简单 GearRefres

swift项目中使用OC/C的方法

假如有个OC类OCViewController : UIViewController类里有两个方法 //swift调用oc或c的混编是比较常用的,反过来的调用很少.这里只写了swift调用oc和c的方式.//OC函数声明- (void)testOC;//C函数声明void testc(); 实现:void testc(){  printf("testc.....................");} -(void)testOC{  NSLog(@"\ntestOC.....

在Windows Phone项目中调用C语言DLL

在Windows Phone项目中调用C语言写的DLL 最近接到一个需求,需要在WP里调用一个C语言写的DLL,并且说Android和iOS都可以,问我WP是否可以这样? 我说我调研一下,就有了下面的文章. 在传统C# WinForm 里调用Win32 DLL都不容易(可能用惯了C#),要用P/Invoke,然后DllImport什么什么,那WP里不是更麻烦? 先看看网上有没有可用的文章,结果还真找到devdiv中的文章,但其中有两处错误,所以我fix bug并且整理一下,然后展示给大家. 1.

JNI_Android项目中调用.so动态库实现详解

转自:http://www.yxkfw.com/?p=7223 1. 在Eclipse中创建项目:TestJNI 2. 新创建一个class:TestJNI.java package com.wwj.jni; public class TestJNI { public native boolean Init(); public native int Add(int x, int y); public native void Destory(); } 以上代码声明三个本地方法. 3. 编译JNI

JNI_Android 项目中调用.so动态库实现详解

转自:http://www.yxkfw.com/?p=7223 1. 在Eclipse中创建项目:TestJNI 2. 新创建一个class:TestJNI.java package com.wwj.jni; public class TestJNI { public native boolean Init(); public native int Add(int x, int y); public native void Destory(); } 以上代码声明三个本地方法. 3. 编译JNI

JNI_Android项目中调用.so动态库实现详解【转】

转自 http://www.cnblogs.com/sevenyuan/p/4202759.html 1. 在Eclipse中创建项目:TestJNI 2. 新创建一个class:TestJNI.java package com.wwj.jni; public class TestJNI { public native boolean Init(); public native int Add(int x, int y); public native void Destory(); } 以上代码