iOS8 – 在swift中使用object-c类

吴统威 on 编程语言 SWIFT | 2015-05-05 08:09:48.0

在IOS8应用中开始使用swift语言编程.那我们怎么在swift中使用Object-c或者在Object-C中使用swift呢?不用担心,可以做到.

苹果公司有一些非常好的文档,在这里.隐藏,如果你想使用一个已经存在的类,执行第二步且跳到第五步.我添加一个显示的老Object-c文件:

#import <Foundation/Foundation.h>

步骤 1:添加一个Objective-C实现 ---.m,

添加一个.m到类中,命名为CustomObject.m


步骤2 :添加桥接头

当添加.m文件时,会弹出一个提示框,像下面的,点击Yes!:


iOS 8 Bridging Objective-C with Swift

怎么创建一个Object-C桥接头的例子,可以查看: How to create an Objective-C Bridging header

如果没有看到提示框,或者意外的删除了桥接头,那添加一个新的.h文件到项目,且命名为<#YourProjectName>-Bridging-Header.h

参照下面图,进行操作

enter image description here

步骤 3:添加Object-C头---.h

添加另外的.h文件和命名为CustomObject.h

步骤 4:创建Object-C类

在 CustomObject.h中

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end

在 CustomObject.m中

#import "CustomObject.h"

@implementation CustomObject : NSObject 

- (void) someMethod {
    NSLog(@"SomeMethod Ran", 0, 0);
}

@end

步骤 5:添加一个类到桥接头

在 项目名称-Bridging-Header.h:

#import "CustomObject.h"

步骤 6:在项目中使用

在 SomeSwiftFile.swift:

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

 

总结:注意桥接头的使用!