How to call Objective-C code from Swift?

This translation from: How do the I Call in Objective-C code from Swift?

In Swift, how does one call Objective -C code? In Swift, how to 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? They can co-exist in an application Apple mentioned, but does that mean you can reuse the old class created by the Objective-C in technology, while building a new class in Swift in it?


#1st Floor

Reference: How https://stackoom.com/question/1ci6z/ call Objective-C code from Swift


#2nd Floor

Apple's Guide to See the Using Swift with Cocoa and Objective-C . See Apple regarding the use of the Swift in conjunction with Cocoa and Objective-C guidelines. 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. This guide covers how to use the Swift the Objective-C and C code, and vice versa, and provides recommendations about how to convert or mix and match items Objective-C / C and Swift components existing project.

The compiler automatically generates Swift syntax for calling C functions and Objective-C methods. Compiler automatically generates a call C functions, and methods of Objective-C syntax Swift. As seen in the documentation, this Objective -C: As shown in the document, the Objective-C:

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

turns into this Swift code: become the Swift Code:

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

Also does the this - Search.com ON Xcode at The Fly -. Quickly the while you CAN use Open File Editing A Swift and of the type AN in Objective-C class name, and the Take IT you'll Swift A-to-ified at The class header Version of Xcode can be immediate translation - you can use the "Quick open" and type Objective-C class name, then it will take you to the head of the class when editing Swift Swift version of the file. (Also by You CAN GET by the this-cmd ON AN Clicking the API Swift File Symbol A in.) And The All the API Reference Documentation The in the iOS. 8 and the OS X-v10.10 (Yosemite) Developer Libraries visible in both IS and Swift in Objective-C Forms (EG UIView). (You can also obtain this information by clicking Swift cmd file API symbol.) iOS 8 and OS X v10.10 (Yosemite) All API reference documentation for developers library in Objective-C and Swift are visible form (e.g. UIView).


#3rd floor

From at The Stock- ET Net Documentation : From the document references:

Any Objective-C framework (or C library) that's accessible as a module can be imported directly into Swift. Any Objective-C frameworks as modules accessible (or C library) can be introduced directly into the 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. This includes all of the Objective-C framework (e.g. Foundation, UIKit and SpriteKit), and General C library that comes with the system. For example, to import Foundation, simply add this import statement to the top of the Swift file you're working in: For example, to import the Foundation, just this Swift import statements to the top of the file you are using:

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. This introduced all Foundation API (including NSDate, NSURL, NSMutableData and all methods, attributes and categories) can be used directly in the Swift.


#4th floor

Using Objective-C Classes in Swift using the Objective-C class of Swift

The If you have have existing AN ** class that you'd like to use, the perform the Step 2 and the then Skip to the Step 5 . ** If you have an existing course you want to use, go to step 2 , and then skip to step 5 . (The For some Cases, the I HAD AN Explicit to the Add #import <Foundation/Foundation.hto AN older Objective-C File.) ** (in some cases, I have to add an explicit Objective-C in the old file #import <Foundation/Foundation.h.) **

Step 1: Add Objective-C Implementation - .m Step 1: Add embodiment -.m Objective-C

A the Add .mFile to your class, and name IT CustomObject.m. Will .madd files to your class, and name it CustomObject.m.

Step 2: Add Bridging Header Step 2: Add bridged title

Adding your the when .mFile, you'll LIKELY BE A HIT with prompt that looks like the this: add .ma file may appear similar to the following tips tips:

Enter here captions

The Click YES ! Click is !

See you at The DID not IF prompt, or Accidentally deleted your Bridging header, the Add A new new .hFile to your IT Project and name <#YourProjectName#>-Bridging-Header.h. If you do not see the prompt, or accidentally deleted bridging the title, add a new item to your the .hfile and name it <#YourProjectName#>-Bridging-Header.h.

In some situations, particularly when working with Objective-C frameworks, you do not add an Objective-C class explicitly and Xcode can not find the linker. In some cases, especially when using Objective-C framework that you without explicitly add the Objective-C class, and can not find Xcode linker. The this Case an In, the Create your .hFile named AS Mentioned above, the then Link the make the Sure you in your target's path the ITS Project Settings like SO: In this case, as described above, create .ha file, and then make sure its path is linked to the objectives of the project setting, as follows:

Enter here captions

Note Note

IT's Best Practice to Link your Project a using at The $(SRCROOT)Macro SO that IF you the Move your Project, or Work ON IT with Others a using A Remote Repository, IT by Will Still Work. Best practice is to use $(SRCROOT)a macro link project to or use remote mobile project when used in conjunction with other repository project, which is still valid. $(SRCROOT)can be thought of as the directory that contains your .xcodeproj file. $(SRCROOT)it can be considered .xcodeproj directory contains the file. It might look like this: It might look like this:

$(SRCROOT)/Folder/Folder/<#YourProjectName#>-Bridging-Header.h

Step 3: Add Objective-C Header - .h Step 3: Add the Objective-C header -.h

Another the Add .hFile name and IT CustomObject.h. Add another .hfile, and name it CustomObject.h.

Step 4: Build your Objective-C Class Step 4: Create your Objective-C classes

In CustomObject.h standingCustomObject.h

#import <Foundation/Foundation.h>

@interface CustomObject : NSObject

@property (strong, nonatomic) id someProperty;

- (void) someMethod;

@end

In CustomObject.m standingCustomObject.m

#import "CustomObject.h"

@implementation CustomObject 

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

@end

Step 5: Add Class to Bridging- Header Step 5: Add a class to Bridging-Header

In YourProject-Bridging-Header.h: standing YourProject-Bridging-Header.h:

#import "CustomObject.h"

Step 6: Use your Object Step 6: Use your object

In SomeSwiftFile.swift: standing SomeSwiftFile.swift:

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

There is no need to import explicitly; need to explicitly import; . The Bridging that apos What IS header for this is the use of the bridge joint.

Using Swift Classes in Objective-C used in the Objective-C class Swift in

Step 1: Create New Swift Class Step 1: Create a new category Swift

A the Add .swiftFile to your Project, and name IT MySwiftObject.swift. An .swiftadd files to your project, and name it MySwiftObject.swift.

In MySwiftObject.swift: standing 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 Step 2: Swift class file into ObjC

In SomeRandomClass.m: standing SomeRandomClass.m:

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

File at The: <#YourProjectName#>-Swift.hShould the Created Automatically BE already in your Project, the even IF you CAN not See IT. Even if you do not see the file, has automatically created a file in your project <#YourProjectName#>-Swift.h.

Step 3: Use your class Step 3: Using the Classroom

MySwiftObject * myOb = [MySwiftObject new];
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);
myOb.someProperty = @"Hello World";
NSLog(@"MyOb.someProperty: %@", myOb.someProperty);

// original
NSString * retString = [myOb someFunction:@"Arg"];
// xcode10 expands the external arg here
NSString * retString = [myOb someFunctionWithSomeArg:@"Arg"];|

NSLog(@"RetString: %@", retString);

Note: Note:

1. CodeCompletion not behaving WAS AS IT Accurately AS the I'd like to. 1. CodeCompletion behavior is not as accurate I hope. On my system, running a quick build with "cmd + r" seemed to help Swift find some of the Objective-C code and vice versa. On my system, using the "cmd + r" Run quickly build seems to help Swift Find Some Objective-C code, and vice versa.

2. the If you the Add A .swiftFile to Project and older GET AN error: dyld: Library not loaded: @rpath/libswift_stdlib_core.dylib, the try Completely Restarting Xcode . 2. If you .swiftadd files to an older project and error appears: dyld: Library not loaded: @rpath/libswift_stdlib_core.dylibPlease try completely restart Xcode .

3. the While IT WAS Originally Pure Swift Possible to use in classes by the using Objective-C The @objcprefix, Swift After 2.0, the this longer Possible IS NO. 3. Although initially used by @objcusing the Objective-C class prefix pure Swift, but after Swift 2.0, this is no longer feasible. See edit history for original explanation. About the original instructions, see the edit history. If this functionality is reenabled in future Swift versions, the answer will be updated accordingly. If in future versions of Swift This feature is re-enabled, the answer will be updated accordingly.


#5th Floor

The Read at The Nice CAN POST by You Swift & Cocoapods . You can read Swift & Cocoapods wonderful article. Basically, we need to create a bridging header file and put all Objective-C headers there. Basically, we need to create a bridge joint document, and place all of the Objective-C header files there. And then we need to reference it from our build settings. Then we need to refer to it from the build settings. After that, we can use the Objective -C code. After that, we can use 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)
  })

Have have the Apple AT A look Also the Document's the Using Swift with Cocoa and Objective-C AS Well. You can also look at Apple's document " will Swift with Cocoa and Objective-C combination ."


#6th floor

I wrote a simple Xcode 6 project that shows how to mix C ++, Objective-C and Swift code: I wrote a simple Xcode 6 project, showing how to mix C ++, Objective-C and Swift Code:

https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console

Particular the In, The Example Calls AN Objective-C and C ++ function from A The Swift . In particular, this example calls Objective-C and C ++ functions from Swift .

The key is to create a shared header , Project-Bridging-Header.h, and put the Objective-C headers there. The key is to create a shared head Project-Bridging-Header.h, which is then placed in Objective-C header.

Please download the project as a complete example . Please download the complete project as an example.

Original articles published 0 · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/p15097962069/article/details/105326292