您的位置:首页 > 移动开发 > Objective-C

160129关于xcode 7中object c与swift相互引用的问题。

2016-01-29 17:16 417 查看
一,在swift文件 中引用object c文件。

在swift文件中创建一个object c类TestSwift2OC,在弹出对话框(Would
you like to configure an Objective an Objective-C bridging header?)

选择Yes 这时会自动生成一个 项目名-Bridging-Header.h文件

#import <Foundation/Foundation.h>

@interface TestSwift2OC : NSObject

-(void)TestOCStr;
@end


#import "TestSwift2OC.h"

@implementation TestSwift2OC

-(void)TestOCStr
{
NSLog(@"这个是OC方法");
}
@end


在Bridging-Header.h文件中把TestSwift2OC.h文件加进来

#import "TestSwift2OC.h"

好了
,我们在swift中可以调用了,试一下

var testSwift2oc=TestSwift2OC()
testSwift2oc.TestOCStr()


一,在object c文件 中引用swift文件。
类似的在object c 项目中引用swift 文件 ,生成一个 继承NSObject swift类。

import UIKit

class TestOC2Swft: NSObject {
func testSwftStr(){
println("这个是Swift方法")
}
}
生成文件时同样会弹出在弹出对话框(Would you like to configure an Objective an Objective-C bridging header?),在xcode6中不需要选择yes.也会把这个swift类加进 系统自动生成的文件 。#import "TestSwiftOC-Swift.h"

SWIFT_CLASS("_TtC22TestObjectCImportSwift9FirtSwift")
@interface TestOC2Swft : NSObject
- (void)testSwftStr;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end


但在Xcode 7.1, 7.2中必须要选中Yes 才能在"TestSwiftOC-Swift.h"加入上面的代码,不然只生成这个文件 没有把这段代码加进来

然后在object 就可以像普通的object c类一样引用swift类

TestOC2Swft *testOC2Swift=[[TestOC2Swft alloc]init];
[testOC2Swift testSwftStr];


在object c中引用Charts时一直没发找到用swift实现的类,最后找到官方文件,原来在同一个工程中引用swift和从另一个工程引用不一样需要

@import 另一个工程的frame

You can import external frameworks that have a pure Objective-C codebase, a pure Swift codebase, or a mixed-language codebase. The process for importing an external framework is the same whether the framework is written in a single language or contains files
from both languages. When you import an external framework, make sure the Defines Module build setting for the framework you’re importing is set to “Yes".

You can import a framework into any Swift file within a different target using the following syntax:

import

FrameworkName


You can import a framework into any Objective-C
.m
file
within a different target using the following syntax:

@import

FrameworkName;

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: