IOS---OC and swift

Source: Internet
Author: User

After the swift language comes out, it may be possible for new projects to be developed directly using swift, but there may be situations in which some classes that have been written with OC or packaged modules are not ready to be written again in Swift, which uses a mash-up. This is allowed in the IOS8. First of all, first of all, research in the same project directory under the mixed use situation. For demonstration. Prepare two classes first is the Swift language class, the file name is Act.swift   [CPP] view plaincopy on code to see the chip derivation to my Code slice import foundation    class 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 for OCChannel.h, the implementation file for the OCCHANNEL.M header file   [CPP] view plaincopy on code to view the snippet derived from my Code slice #import       @interface occhannel:nsobject    @property (nonatomic,retain) nsstring *channelname;  &nbs P -(NSString *) Channelchange: (Nsinteger) channels;    @end  

Implementation file     [CPP] view plaincopy on code to see a snippet derived from my Code slice #import "OCChannel.h"   #import "swiftmodule-swift.h" and nbsp   @interface Occhannel ()   {      act     *act; //swift Classes  }  @end     @implementation occhannel   -(ID) init  {      if (SE LF = [Super init]) {          NSLog (@ "OC Constructor is called.");          /use of 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 }& nbsp  -(NSString *) Channelchange: (nsinteger) channels  {      return [Act Hasact:channels]; }    @end  

This occhannel is a class act written by Swift. Mainly to demonstrate that in the same project, the Swift class calls OC, while the OC class also calls Swift. Thus forming a mixed-writing pattern.

Here are the steps: 1. Create a new Swift project: I have a project named Mixdemo.

Built after the project:

2. Is the introduction of the previous two classes, we first to each one. Because it is swift, we first used the OC file in Swift Engineering to use OC in a mixed swift in the way that the header and. m files were 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 the OC. In fact, Swift also needs to be accessed with a header file, but it is no longer necessary to import it explicitly using import. There are two ways to implement the generation of this header file. Mode one: In a new swift, the bridge header file is automatically added using the first new prompt.

Click OK to generate a header file. After the construction of the project:

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

After the above steps, the bridge file is ready to go to the swift class to call the OC header file to use the import "" to write to this bridge file. It's like: [CPP] View plaincopy on code to see the chip derivation to my Code slice///Use the This file to import your target's public headers so you would  Like to expose to Swift. Mixdemo/mixdemo-bridging-header.h #import "OCChannel.h"

Again, once you know the relationship of this swift search header file, you don't have to bother with the-bridging-header.h file. You can build one by hand and take your favorite name. such as:   Two: Create a new header file named: OCContainerHeader.h

Well, the above setup will completely satisfy the class that Swift uses OC to write.   [CPP] view plaincopy on code to view a snippet derived from my Code slice import uikit    class Viewcontroller:uiviewcontroller {  & nbsp;                                  override func Viewdidload () {           super.viewdidload ()           /additional setup after loading the view, typically from a nib.        &nbsp ;  //Call OC class           var channel = Occhannel ()            println (channel. Channelchange (Ten)           println (channel. Channelchange (2))      }        override func didreceivememorywarning () {      &NBSp;    super.didreceivememorywarning ()          //Dispose of Any resources, can be recreated.     }     } 

Okay, here's another look at how OC calls the Swift-written class. (In fact, if you are 1:1 copy me this demo, which congratulations you, in the above you will compile does not pass.) Because my OC class refers to a class written by Swfit, you have to comment on which act's class you want to run. )

How OC calls the Swift write class OC to be used, there must be 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 quite special. Because the mechanism inside the header file is automatically generated, in unfamiliar, not recommended handwriting. How to produce this header file. (Note that the system-Set header file is not visible in the project.) ) Generation Step: 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 not find this file in the entire project, but the use of cmd+ mouse click to see the contents of this header file.

In this way, in the case of Swift to use OC in the project, the need to use the OC class header file, all written in the mixdemo-bridging-header.h. Also if the use of the Swift class OC, only need to clean one, and then make up, but do not forget to import swiftmodule-swift.h Oh (name pick, but-swift.h is fixed), there is another need to pay attention to the reader. Note: If a class that is written with Swift does not follow a derived class from NSObject or NSObject, then the corresponding transformation class will not be generated after compilation. This makes it possible for OC to not find the corresponding declaration. As in my example, class Act would not be compiled into Swiftmodule-swift.h, but written as Class Act:nsobject, you can compile the corresponding declaration. You can also use @objc to declare, but this is still the same, the class best inherit nsobject down. Just like the following:     [CPP] view plaincopy on code to see a snippet derived from my Code slice import foundation    @objc (ACT)     class A ct   {      func hasact (tag:int), string      {           switch (TAG)           {           case 1:return ' Movie '           case 2: Return "CCTV"           case 3:return "Sport TV"            Default:return "Area TV"   &Nbsp;      }     }        @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 you will find act = [Act Alloc]init] when you use it; Error, can not find alloc, it is recommended that everyone still inherit nsobject.

IOS---OC and swift

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.