Initial Swift Language learning note 9 (OC and Swift Miscellaneous)

Source: Internet
Author: User

Author: fengsh998 Original address:http://blog.csdn.net/fengsh998/article/details/34440159 Reprint Please indicate the source Assuming that the article is helpful to you, please leave a message or follow the public account fengsh998 to support me, thank you!



After the swift language comes out, it may be possible for new projects to be developed directly using Swift. However, you may encounter some situations in the process. Some classes or encapsulated modules that have been written in OC. Don't want to write again in Swift. Use mixed. This is agreed in the IOS8.

First of all, first of all, to study the same project folder under the mixed use situation.

For demonstration.

Prepare two classes first

The first is the Swift language class, the file name is called Act.swift

Import Foundationclass act:nsobject{    func hasact (tag:int), String    {        switch (tag)        {case        1: Return "Movie" Case        2:return "CCTV" Case        3:return "Sport TV"        default:return "area TV"        } Init ()    {        println ("Act constructor is called.")    }        Deinit    {        println ("act destroyed is called.")    }}

The second is the class header file written with OC as OCChannel.h, implementing the file as OCCHANNEL.M

Header file

#import <Foundation/Foundation.h> @interface occhannel:nsobject@property (nonatomic,retain) NSString * channelname;-(NSString *) Channelchange: (nsinteger) channels; @end

Implementation file

#import "OCChannel.h" #import "Swiftmodule-swift.h" @interface Occhannel () {    Act     *act;  Swift's Class} @end @implementation occhannel-(ID) init{    if (self = [super init]) {        NSLog (@ "OC Constructor is called.") ;        Use Swift class        act = [[Act Alloc]init];    }    return self;} -(void) dealloc{    NSLog (@ "OC destroyed is called.");    [Act Release];//arc not use    //[super Dealloc];//arc not use}-(NSString *) Channelchange: (Nsinteger) channels{< C12/>return [Act Hasact:channels];} @end

This occhannel is a class act written by Swift.

Mainly to demonstrate that in the same project project, the Swift class calls OC, and the OC class also calls Swift at the same time. Thus forming a mixed-writing pattern.


Here are the detailed steps:

1. Create a new swiftproject: I am here project named Mixdemo

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>

When you are finished building project:


2. Is the introduction of the previous two classes, we first to each one.

Since the building is swift, we first use the Swiftproject to refer to the OC file for a mixed

Using OC in Swift

First, the way the header files and. m files are no longer used in swift.

Therefore, you do not need to import the header file using import "".

How swift can access the class declaration of OC.

In fact, Swift is also required to use the head file to access the interview. You simply no longer have to use import in an explicit manner.

There are two ways to implement the generation of this header file.

Way One: in a brand new Swift. Take the initiative to join the bridge header file yourself with the first new hint.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>



Click OK this will generate a header file with <produceName-Bridging-Header.h>.

After the project is built:

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>

Here is a place to note is the Targets->build settings->object-c bridging header is set to which bridge header file can be.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>


After these steps, the bridging file is ready to

Let's get the OC header file you want to call in the Swift class and use the import "" to write to the bridge file. Just like:

Use the this  file to import your the target ' s public headers so would like to expose to Swift.//mixdemo/mixdemo-bri Dging-header.h#import "OCChannel.h"

Similarly, once you know the relationship of this swift search header file, you don't have to bother with this-bridging-header.h file. Be able to build one by hand and take your favorite name. Such as:

Way two:

Create a new header file named: OCContainerHeader.h

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvzmvuz3nootk4/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center "/>


All right. The above setting completely satisfies the class that Swift uses OC to write.

Import Uikitclass Viewcontroller:uiviewcontroller {                                override func Viewdidload () {        super.viewdidload ()        // Additional setup after loading the view, typically from a nib.        Call OC class        var channel = Occhannel ()        println (channel. Channelchange (Ten))        println (channel. Channelchange (2)    }}    override Func didreceivememorywarning () {        super.didreceivememorywarning ()        // Dispose of any resources the can be recreated.    }}

Okay, here's another look. how OC Invokes Swift-written classes。 Actually Suppose you are 1:1 copy me this demo, which congratulations you, in the above you will compile does not pass. Since my OC class refers to a class written by Swfit, you have to gaze at which act class you want to execute. )


How OC invokes Swift-written classes

OC wants to use. You must have a header file. The swift file does not have a header file, where we must also produce a header file. However, the header file for the OC call to Swift is more special. Because the mechanism inside the header file is self-generated, in unfamiliar, not recommended handwriting.

How to produce this header file.

Note The system-Set header file is not visible in project.

Production steps:

Select targets->build Settings->packing->product module name, which is very important the name of the swift header file is named after this.



Although you see this import "Swiftmodule-swift.h" in the picture, but you can't find this file in the whole project, but can use cmd+ mouse click to see the contents of this header file.



In this way, in project, if you want to use OC in the case of Swift, the header files of the OC class that need to be used are all written in Mixdemo-bridging-header.h.

The same assumes that the Swift class is used in OC. Just need to clean one, then make up can, but do not forget to import swiftmodule-swift.h Oh (name pickup. But the-swift.h is fixed) and the other one needs the attention of the reader.

Note:

Classes that are written in Swift. Assuming that you do not follow a derived class from NSObject or NSObject, the corresponding transformation class will not be generated after compilation.

This makes the corresponding declaration not found in OC.

As in my example, class Act is not compiled into Swiftmodule-swift.h, but written as Class Act:nsobject, the corresponding declaration can be compiled. It is also possible to use @objc to declare, but this is still the same, the class best inherit nsobject down.

Just like the following:

Import FOUNDATION@OBJC (ACT) class Act {    func hasact (tag:int), String    {        switch (tag)        {case        1: Return "Movie" Case        2:return "CCTV" Case        3:return "Sport TV"        default:return "area TV"        }    @ OBJC (init)//Originally thought to add this alloc can be found, but not.

。。 Init () { println ("Act constructor is called.") } Deinit { println ("act destroyed is called.") }}


But when you use it, you'll find

act = [[Act Alloc]init]; Error, unable to find Alloc. Therefore, we suggest that we should inherit nsobject.



All right, I'll write it down here today. Then look at the mixing of the frameworks.




Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Initial Swift Language learning note 9 (OC and Swift Miscellaneous)

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.