Swift and Objective-C hybrid programming, swiftobjective-c

Source: Internet
Author: User

Swift and Objective-C hybrid programming, swiftobjective-c

1. First open Xcode6 and create a project. Here I use the default Objective-C programming language. The project name is "SwiftAndObjective ".

2. To use the Swift demo in OC, you need to create the following classes.

A) create an Objective-C class that inherits from NSObject and its name is OCTypeClass. Therefore, two corresponding classes are automatically generated. m and. h file, which is very familiar with Objective-C.

B) try your best to create a Swift class named SwiftFile1. When you click Create, a prompt will pop up asking if you want to create a hander. h file. You must select here. Because if you want to use the Objective-C class in Swift, this is a necessary file and you will discuss it later. A SwiftFile1.swift file and a header file are created.

C) to describe the relationship between the public, private, and default access controllers, you need to create another Swift file named SwiftFile2, which generates a SwiftFile2.swift file.

The file has been created.


3. classes need to be defined (because swift can not inherit any classes, but if it needs to be used by Objective-C, the alloc, new, and other methods we use are inherited from NSObject, so I have inherited NSObject from these classes in Swift ).

Create the following class in the SwiftFile1.swift File

import Foundation@objc public class PublicObjcTypeSwiftClass1: NSObject {    var property1: Int = 0}@objc class ObjcTypeSwiftClass1: NSObject {    var property1: Int = 0}@objc private class ObjcPrivateTypeSwiftClass1: NSObject {    var property1: Int = 0}public class PublicSwiftClass1 : NSObject {    var property1: Int = 0}class SwiftClass1: NSObject {    var property1: Int = 0}private class PrivateSwiftClass1: NSObject {    var property1: Int = 0}


Create the following class in SwiftFile2.swift

<pre name="code" class="objc">import Foundation@objc public class PublicObjcTypeSwiftClass2: NSObject {    var property1: Int = 0    //var ocClass: OCTypeClass = OCTypeClass()        //func test() {    //    ocClass.property1 = 0    //}}@objc class ObjcTypeSwiftClass2: NSObject {    var property1: Int = 0}@objc private class ObjcPrivateTypeSwiftClass2: NSObject {    var property1: Int = 0}public class PublicSwiftClass2: NSObject {    var property1: Int = 0}class SwiftClass2: NSObject {    var property1: Int = 0}private class PrivateSwiftClass2: NSObject {    var property1: Int = 0}


 

4. Because the corresponding class is automatically generated after the OC file is defined, you do not need to define it again.

#import "OCTypeClass.h"#import "SwiftAndObjective-Swift.h"@implementation OCTypeClass- (void)test{    PublicObjcTypeSwiftClass1 *type = [[PublicObjcTypeSwiftClass1 alloc] init];    type.property1 = 0;            ObjcTypeSwiftClass1 *type2 = [[ObjcTypeSwiftClass1 alloc] init];    type2.property1 = 0;}@end


5. Open the OCTypeClass. m file and we need to reference the class in the Swift file. You can use "project name + '-' + Swfit. h "is introduced to the public class and marked as @ objc (marked as @ objc class, even if the public mark is not displayed, it will be used by the Objective-C class ). The specific code below (note that when # import "" is used, Xcode of the current version does not automatically recognize the required Swift header name. You need to manually write the code yourself. Note: do not write the wrong Project name. If you confirm that the Project is correct, but keep reporting errors, You can refresh the Project, or restart and re-build: Project-Clean, Project-Build, big deal restart Xcode ).


6. After that, you can view the Objective-C Class automatically generated by xcode in the form of source code (command + left mouse button.

// Generated by Swift version 1.1 (swift-600.0.54.20)#pragma clang diagnostic push#if defined(__has_include) && __has_include(<swift/objc-prologue.h>)# include <swift/objc-prologue.h>#endif#pragma clang diagnostic ignored "-Wauto-import"#include <objc/NSObject.h>#include <stdint.h>#include <stddef.h>#include <stdbool.h>#if defined(__has_include) && __has_include(<uchar.h>)# include <uchar.h>#elif !defined(__cplusplus) || __cplusplus < 201103Ltypedef uint_least16_t char16_t;typedef uint_least32_t char32_t;#endiftypedef struct _NSZone NSZone;#if !defined(SWIFT_PASTE)# define SWIFT_PASTE_HELPER(x, y) x##y# define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y)#endif#if !defined(SWIFT_METATYPE)# define SWIFT_METATYPE(X) Class#endif#if defined(__has_attribute) && __has_attribute(objc_runtime_name)# define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X)))#else# define SWIFT_RUNTIME_NAME(X)#endif#if !defined(SWIFT_CLASS_EXTRA)# define SWIFT_CLASS_EXTRA#endif#if !defined(SWIFT_PROTOCOL_EXTRA)# define SWIFT_PROTOCOL_EXTRA#endif#if !defined(SWIFT_CLASS)# if defined(__has_attribute) && __has_attribute(objc_subclassing_restricted) #  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA# else#  define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA# endif#endif#if !defined(SWIFT_PROTOCOL)# define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA#endif#if !defined(SWIFT_EXTENSION)# define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__)#endif#if !defined(OBJC_DESIGNATED_INITIALIZER)# if defined(__has_attribute) && __has_attribute(objc_designated_initializer)#  define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer))# else#  define OBJC_DESIGNATED_INITIALIZER# endif#endif#if defined(__has_feature) && __has_feature(modules)@import ObjectiveC;#endif#pragma clang diagnostic ignored "-Wproperty-attribute-mismatch"#pragma clang diagnostic ignored "-Wduplicate-method-arg"SWIFT_CLASS("_TtC17SwiftAndObjective19ObjcTypeSwiftClass1")@interface ObjcTypeSwiftClass1 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective19ObjcTypeSwiftClass2")@interface ObjcTypeSwiftClass2 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective25PublicObjcTypeSwiftClass1")@interface PublicObjcTypeSwiftClass1 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective25PublicObjcTypeSwiftClass2")@interface PublicObjcTypeSwiftClass2 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective17PublicSwiftClass1")@interface PublicSwiftClass1 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective17PublicSwiftClass2")@interface PublicSwiftClass2 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective11SwiftClass1")@interface SwiftClass1 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@endSWIFT_CLASS("_TtC17SwiftAndObjective11SwiftClass2")@interface SwiftClass2 : NSObject@property (nonatomic) NSInteger property1;- (instancetype)init OBJC_DESIGNATED_INITIALIZER;@end#pragma clang diagnostic pop


7. The following describes how to use the Objective-C Class in the Swift file.

A) Open xcode's automatically generated SwiftAndObjective-Bridging-Header.h file and import the class exposed to swift.

Here we use the class just defined for convenience, just for Demonstration:

# Import "OCTypeClass. h"

B) Then we don't need to do anything. Implement it directly in the Swfit file.

import Foundation@objc public class PublicObjcTypeSwiftClass2: NSObject {    var property1: Int = 0    var ocClass: OCTypeClass = OCTypeClass()        func test() {        ocClass.property1 = 0    }}@objc class ObjcTypeSwiftClass2: NSObject {    var property1: Int = 0}@objc private class ObjcPrivateTypeSwiftClass2: NSObject {    var property1: Int = 0}public class PublicSwiftClass2: NSObject {    var property1: Int = 0}class SwiftClass2: NSObject {    var property1: Int = 0}private class PrivateSwiftClass2: NSObject {    var property1: Int = 0}


Note:

1. If you want to expose a Swfit class to Objective-C, you need to mark @ objc.

2. For private Swift classes, they can only be used in the defined Swift file.

3. The class in a Swift file can only access the public class defined in the external Swift file.


I almost ignored the most important point: if you have any questions or errors, please correct them or contact me.


Sample Code: Code

Http://download.csdn.net/detail/liyan223/8070805








Objective-C and C ++ mixed programming (iPhone/MacOS/iPad)

Objc can use most c syntax .. Change the cpp file name to. m.
Why can't c ++ use try/catch? It is his own.
Objc hasn't heard of stl. He has his own inheritance and you will know it when you use it. Although it can be written in c ++, it is only available, and people must use their own syntax.
As for mac systems, it seems that it is necessary for Apple machines to facilitate Apple development. General computers do not seem to work. At least I have to assign one million Apple servers to each of them.

How to mix objective-c and Cpp for programming?

First, your project must support C ++ writing. There are two ways to achieve this:
(1) convert the appDelegate. m file to the appDelegate. mm file.
(2) Select Build Settings> Compiler for c/c ++/objective-c of the project and set it to Apple LLVM Compiler 3.0.

Then, set the type of the. m file with the C ++ Implementation Method to obejctive c ++ source.
In this way, you can implement mixed encoding.

Hope to help you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.