如何从 Swift 调用 Objective-C 代码

In the new Swift language from Apple, how does one call Objective-C code?

Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst building new classes in Swift?

The Reasoning

Objective-C is a platform-independent language, whereas Swift is platform-dependent. Writing non-platform-dependent code (business logic libraries) in Swift would thus not be wise. However, writing platform-dependent code in it (interface related for example) would be perfectly fine. Not to say it would be a good idea, however it is definitely an interest.

转载于:https://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift

csdnceshi64
游.程 Is "The Reasoning" section still needed ?
4 年多之前 回复
csdnceshi63
elliott.david yes. And that's why I did not flag the question. I just thought RTFM in my mind.
大约 6 年之前 回复
csdnceshi63
elliott.david exactly what is missing from Objective C that prevents it from being a platform independent language? The language and the language standard libraries are open source. You can use Objective C in and for Windows, Os X, Linux, BSD, Solaris and any other platform supported by either GCC or LLVM. You can easily port Objective C to any platform with a decent C compiler even if it's supported by neither GCC nor LLVM. I do not see how it could be more platform independent than this.
大约 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 1) Repetition of documentation resources is something StackOverflow is perfectly fine with. And apparently I was not the only one wondering as most people come here from Google. 2) Read the bounty description ;-)
大约 6 年之前 回复
csdnceshi63
elliott.david Interesting that this question gets so many upvotes and a bounty. When I first saw it I just thought: RTFM. As posed it really show no research as currently there are only two or three resources that officially document Swift, and one of them is fully dedicated to exactly this (and is linked to in the first comment).
大约 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 As in... you would prefer the term cross-platform language? But even swift is cross platform, so which term would you use for all the languages which can be run on nearly any platform?
大约 6 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 I totally agree but still calling it a platform independent language would be too much.
大约 6 年之前 回复
weixin_41568196
撒拉嘿哟木头 Just that for example with gcc you can compile Objective C code just as easily on linux as you can on a mac, so you can use the same code and executables on a lot of platforms (only match for this is java and only thing that beats it is the web stack).
大约 6 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Question sounds good but one thing is bothering me -- What do you mean by "Objective-C is a platform-independent language"?
大约 6 年之前 回复
csdnceshi77
狐狸.fox developer.apple.com/library/prerelease/ios/documentation/Swift/…
大约 6 年之前 回复
weixin_41568184
叼花硬汉 See Apple's guide to Using Swift with Cocoa and Objective-C.
大约 6 年之前 回复

15个回答

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 <Foundation/Foundation.h to an older Objective-C File.) **

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:

Enter image description here

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 Objective-C 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:

Enter image description here

Note

It's best practice to link your project using the $(SRCROOT) macro so that if you move your project, or work on it with others using a remote repository, it will still work. $(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 <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

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

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

Note:

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

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

3. While it was originally possible to use pure Swift classes in Objective-C by using the @objc prefix, after Swift 2.0, this is no longer possible. See edit history for original explanation. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly.

csdnceshi76
斗士狗 Thanks..it saves lots of time.
接近 2 年之前 回复
weixin_41568126
乱世@小熊 Works for 100%. One of the rarest cases. If you want to make this simpler you can: *create Obj.-C file *bridging-header will be generated. Describe all function in the generated file.
大约 2 年之前 回复
csdnceshi56
lrony* that question is more about ObjC in general. If you import in the .h file, then all subsequent imports of that file will also import the other file. This can be useful if one object always needs another, but it can also lead to circular dependencies where A.h imports B.h imports C.h imports A.h. By putting it in the .m file, we keep it private to this class and subsequent imports don't also import that file. In Swift here, if we have Object.{h,m} and we imported in Object.h, then every time somebody imported Object.h in another file, they'd also import all Swift files.
2 年多之前 回复
csdnceshi52
妄徒之命 But why not put it in the .h file?
2 年多之前 回复
csdnceshi56
lrony* the system will generate a "bridging header" that exposes the accessible swift code to ObjC. This needs to be imported as any other file would be. For example, import OtherObject.h to import an ObjC class header. For Swift, we don't import classes individually, but rather need to import all accessible objects
2 年多之前 回复
csdnceshi52
妄徒之命 Why the hell does the -Swift.h file go into the .m file?
2 年多之前 回复
csdnceshi72
谁还没个明天 Thanks @Logan this worked for me but the only thing I Noticed different is that with xcode 7.3 when you add .m or .h files there is no pop up coming for creating the bridging header you have to manually go to Build Settings and do it or may be something is wrong with my project settings :).
4 年多之前 回复
csdnceshi56
lrony* - Good catch, would you suggest leaving a comment indicating that it's no longer relevant >Swift2.0, or removing it completely.
4 年多之前 回复
csdnceshi68
local-host In SomeSwiftFile.swift: I got this: Expected declaration on "instanceOfCustomObject.someProperty = "Hello World" Why?Thanks.
4 年多之前 回复
csdnceshi56
lrony* - Can you go to your build settings and ensure that your Product Module Name is what you expect, the syntax is really #import "ProductModuleName-Swift.h, it just defaults to project name and most people don't change it.
接近 5 年之前 回复
csdnceshi54
hurriedly% I my case Using Swift Classes in Objective-C. But get the error file not found when import #import "<#ProjectName#>-Swift.h". Please help me resolve this.
接近 5 年之前 回复
csdnceshi56
lrony* in objective-c it's convention to name the files after the name of the class, and there's rarely more than one class per file. So yes, you could name it anything, but I wouldn't recommend it. If you want more than one class, create a new .h and .m for each class.
大约 5 年之前 回复
weixin_41568131
10.24 why did you name it CustomClass.m and CustomClass.h? Couldn't this be named anything? What do I name these files if I want to create more than one?
大约 5 年之前 回复
csdnceshi56
lrony* - I get asked that all the time! It's an awesome little app called licecap: cockos.com/licecap
大约 5 年之前 回复
csdnceshi51
旧行李 what tool you used to create this GIF?
大约 5 年之前 回复
csdnceshi67
bug^君 This was critical to add to my Objective C files that I wanted to import into Swift. I missed it and wasted a lot of time: #import <Foundation/Foundation.h>
5 年多之前 回复
csdnceshi79
python小菜 If importing a Objective C framework into Swift, make sure to import all frameworks that the Obj C framework depends on into your project (in Build Phases -> Link Binary With Libraries), then add #import's for those to a prefix header file, which must be added to your project in build settings (in the Prefix Header field). This includes frameworks like UIKit and Foundation, even if those are already used from within Swift. This tripped me up for hours, and no one seems to have documented these steps.
5 年多之前 回复
csdnceshi56
lrony* - If those dependencies are included internally within the library, it should be fine as long as they're included in the project. If you need to access those libraries externally, I'm not positive, but I believe that as long as they are imported in the same header, you should be ok.
接近 6 年之前 回复
csdnceshi75
衫裤跑路 What if the Objective C library has other Objective C dependencies?
接近 6 年之前 回复
weixin_41568184
叼花硬汉 i'm having a class with ten obj c files, but i don't know how to call it with only one customobject file. the class i'm trying to call is AMSlideout, can you give me an example about it?
接近 6 年之前 回复
csdnceshi56
lrony* - Thanks for pointing this out! If you look at the bottom of that article, the author attributes this post.
大约 6 年之前 回复
weixin_41568174
from.. The following blog entry is copied from a portion of this post, or vice versa: ios-blog.co.uk/tutorials/…
大约 6 年之前 回复
csdnceshi60
℡Wang Yan Thank Logan. issue fixed by creating new project and added bridge header file.
大约 6 年之前 回复
csdnceshi56
lrony* - Look at Step 2. Just add a '.h' w/ appropriate name.
大约 6 年之前 回复
csdnceshi60
℡Wang Yan Guys I am new to iOS development. I am using Swift and trying to added XMLRPC libraries to my project. Xcode 6 not giving prompt for generating bridge-header file. Please help me on this
大约 6 年之前 回复
csdnceshi56
lrony* - I added an example with a pure swift class since this question has become so popular. Thanks for the addition!
大约 6 年之前 回复
csdnceshi78
程序go See also: WWDC 2014 Session 406: Integrating Swift with Objective-C
大约 6 年之前 回复
csdnceshi56
lrony* - Got it from here: developer.apple.com/library/prerelease/ios/documentation/Swift/…"
大约 6 年之前 回复
csdnceshi74
7*4 By the way, where did you pull this information from (that <#YourProjectName#>-Swift.h exists)?
大约 6 年之前 回复
csdnceshi56
lrony* - I don't know where it is in the directory, but it's generated automatically. The only way that I've been able to actually see it is when I had an error on it and I was able to click through the debugger to the file. Let me know if you find it.
大约 6 年之前 回复
csdnceshi74
7*4 Where is this <#YourProjectName#>-Swift.h? Is it generated at compile time?
大约 6 年之前 回复
csdnceshi56
lrony* - That's good to know, thanks for the addition :)
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ You are right. You only need to specify it if you don't use Cocoa objects. 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.
大约 6 年之前 回复
csdnceshi56
lrony* -- I didn't find it necessary to do that, is there a specific use case you're referring to?
大约 6 年之前 回复
csdnceshi59
ℙℕℤℝ It is important you need to annotate methods with @objc or Swift methods won't be visible from Objective-C.
大约 6 年之前 回复

See Apple's guide to Using Swift with Cocoa and Objective-C. This guide covers how to use Objective-C and C code from Swift and vice versa and has recommendations for how to convert a project or mix and match Objective-C/C and Swift parts in an existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. As seen in the documentation, this Objective-C:

UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

turns into this Swift code:

let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

Xcode also does this translation on the fly — you can use Open Quickly while editing a Swift file and type an Objective-C class name, and it'll take you to a Swift-ified version of the class header. (You can also get this by cmd-clicking on an API symbol in a Swift file.) And all the API reference documentation in the iOS 8 and OS X v10.10 (Yosemite) developer libraries is visible in both Objective-C and Swift forms (e.g. UIView).

csdnceshi71
Memor.の this answer is suit for the above question?
2 年多之前 回复
csdnceshi53
Lotus@ The direct link to Apple documentation how to integrate Swift in existing project: developer.apple.com/library/prerelease/ios/documentation/Swift/…
大约 6 年之前 回复
csdnceshi62
csdnceshi62 What, no Swift syntax highlighting on SO? This language has been out for all of two hours — that's forever in Internet years! ;)
大约 6 年之前 回复

Quote from the documentation:

Any Objective-C framework (or C library) that’s accessible as a module can be imported directly into Swift. This includes all of the Objective-C system frameworks—such as Foundation, UIKit, and SpriteKit—as well as common C libraries supplied with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you’re working in:

import Foundation

This import makes all of the Foundation APIs—including NSDate, NSURL, NSMutableData, and all of their methods, properties, and categories—directly available in Swift.

Just a note for whoever is trying to add an Objective-C library to Swift: You should add -ObjC in Build Settings -> Linking -> Other Linker Flags.

You can read the nice post Swift & Cocoapods. Basically, we need to create a bridging header file and put all Objective-C headers there. And then we need to reference it from our build settings. After that, we can use the Objective-C code.

let manager = AFHTTPRequestOperationManager()
manager.GET(
  "http://example.com/resources.json",
  parameters: nil,
  success: { (operation: AFHTTPRequestOperation!,
              responseObject: AnyObject!) in
      println("JSON: " + responseObject.description)
  },
  failure: { (operation: AFHTTPRequestOperation!,
              error: NSError!) in
      println("Error: " + error.localizedDescription)
  })

Also have a look at Apple's document Using Swift with Cocoa and Objective-C as well.

  1. Create a .h file from NewFile -> Source -> header file
  2. Then save the name of file Your_Target_Name-Bridging-Header.h People here gets common mistake by taking their project name but it should be the Project's Target's name if in case both are different, generally they are same.
  3. Then in build settings search for Objective-C Bridging Header flag and put the address of your newly created bridging file, you can do it right click on the file -> show in finder -> drag the file in the text area then the address will be populated.
  4. Using #import Your_Objective-C_file.h
  5. In the swift file you can access the ObjC file but in swift language only.

One more thing I would like to add here:

I am very thankful to @Logan's answer. It helps a lot to create a bridge file and setups.

But after doing all these steps I'm still not getting an Objective-C class in Swift.

I used the cocoapods library and integrated it in my project. Which is pod "pop".

So if are using Objective-C pods in Swift then there may be a chance that you can not able to get or import the classes into Swift.

The simple thing you have to do is:

  1. Go to <YOUR-PROJECT>-Bridging-Header file and
  2. Replace the statement #import <ObjC_Framework> to @import ObjC_Framework

For example: (Pop library)

Replace

#import <pop/POP.h>

with

@import pop;

Use clang import when #import is not working.

csdnceshi59
ℙℕℤℝ Use clang import when #import is not working. what? Didn't just say we should use @import ?!
3 年多之前 回复

After you created a Bridging header, go to Build Setting => Search for "Objective-C Bridging Header".

Just below you will find the ""Objective-C Generated Interface Header Name" file.

Import that file in your view controller.

Example: In my case: "Dauble-Swift.h"

eEter image description here

Click on the New file menu, and chose file select language Objective. At that time it automatically generates a "Objective-C Bridging Header" file that is used to define some class name.

"Objective-C Bridging Header" under "Swift Compiler - Code Generation".

Here are step-by-step instructions for using Objective-C code (in this case, a framework provided by a third-party) in a Swift project:

  1. Add any Objective-C file to your Swift project by choosing File -> New -> New File -> Objective-C File. Upon saving, Xcode will ask if you want to add a bridging header. Choose 'Yes'. Gif: adding empty file to project and generating bridging header http://www.derrrick.com/stackoverflow/1-empty-file.gif

In simple steps:

  1. A prompt appears, and then click on OK... If it does not appear, then we create it manually like in the following... Create one header file from iOS source and give the name ProjectName-Bridging-Header (example: Test-Bridging-Header), and then go to build setting in the Swift compiler code -> Objective-C bridge add Objective-C bridge name ..(Test/Test-Bridging-Header.h). Yeah, that's complete.

  2. Optionally, delete the Objective-C file you added (named "anything" in the GIF image above). You don't need it any more.

  3. Open the bridging header file -- the filename is of the form [YourProject]-Bridging-Header.h. It includes an Xcode-provided comment. Add a line of code for the Objective-C file you want to include, such as a third-party framework. For example, to add Mixpanel to your project, you will need to add the following line of code to the bridging header file:

    #import "Mixpanel.h"
  4. Now in any Swift file you can use existing Objective-C code, in the Swift syntax (in the case of this example, and you can call Mixpanel SDK methods, etc.). You need to familiarize yourself with how Xcode translates Objective-C to Swift. Apple's guide is a quick read. Or see this answer for an incomplete summary.

Example for Mixpanel:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    Mixpanel.sharedInstanceWithToken("your-token")
    return true
}

That's it!

Note: If you remove the bridging header file from your project, be sure to go into Build Settings and remove the value for "Objective-C Bridging Header" under "Swift Compiler - Code Generation".

共15条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐