OC and Swift

Source: Internet
Author: User

Turn: Original address: http://blog.csdn.net/fengsh998/article/details/34440159

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 in OC or packaged modules are not ready to be written again in Swift, so use a mash-up. This is allowed in iOS.

First of all, first of all, research in the same project directory under the mixed use situation.

For demonstration. Prepare two classes first

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

Import Foundationclassact: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*channelname; -(NSString *) Channelchange: (nsinteger) channels; @end

Implementation file

#import "OCChannel.h"#import "swiftmodule-swift.h"@interfaceOcchannel () {Act*act;//Swift's class}@end@implementationOcchannel- (ID) init{if(self =[Super Init]) {NSLog (@"OC Constructor is called."); //using the Swift classact =[Act Alloc]init]; }    returnSelf ;}- (void) dealloc{NSLog (@"OC destroyed is called."); //[Act release];//ARC not use//[Super Dealloc];//ARC not use}-(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 specific steps:

1. Create a new Swift project: I'm here for the project named Mixdemo.

Built after the project:

2. Is the introduction of the previous two classes, we first to each one. Because it's swift, we'll start by referencing OC files in Swift Engineering

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 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 this will generate a header file with <produceName-Bridging-Header.h>.

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 be

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

[CPP]View PlainCopy
    1. //
    2. Use the This file to import your target's public headers so would like to expose to Swift.
    3. Mixdemo/mixdemo-bridging-header.h
    4. #import "OCChannel.h"


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

Way 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
  1. Import UIKit
  2. Class Viewcontroller:uiviewcontroller {
  3. Override Func Viewdidload () {
  4. Super.viewdidload ()
  5. additional setup after loading the view, typically from a nib.
  6. //Call OC class
  7. var channel = Occhannel ()
  8. println (channel. Channelchange (10))
  9. println (channel. Channelchange (2))
  10. }
  11. Override Func didreceivememorywarning () {
  12. Super.didreceivememorywarning ()
  13. //Dispose of any resources, can be recreated.
  14. }
  15. }


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 invokes Swift-written classes

To use OC, 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 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.) )

Production steps:

Select targets->build Settings->packing->product module name, which is important the name of the swift header 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:

Import FOUNDATION@OBJC (ACT)classAct {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 it comes to use, you'll find

act = [[Act Alloc]init]; Error, can not find alloc, it is recommended that everyone still inherit nsobject.

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.