Swift's compatibility with Objective-c "Black Magic": @objc and dynamic

Source: Internet
Author: User

Although the original intention of Swift language is to be able to get rid of the heavy historical burden and restraint of objective-c, but it is undeniable that after more than 20 years of baptism, the COCOA framework has long been branded an indelible mark of objective-c. Countless third-party libraries are written in objective-c, and these accumulations can be underestimated by no one. Therefore, in the initial version, Swift had to consider compatibility with objective-c.

Apple's approach is to allow us to use Swift and objective-c for development in the same project. In fact, the objective-c files and Swift files in a project are in two different worlds, and in order for them to be interconnected, we need to add some bridges.

First we can easily use the OBJECTIVE-C code in Swift by adding the {Product-module-name}-bridging-header.h file and filling in the header file name that you want to use. Xcode in order to simplify this setting, even the first time in the Swift project to import the Objective-c file will be the active box to ask whether to automatically create this file, can be said to be very convenient.

But if you want to use Swift's type in objective-c, things are a bit more complicated. If it is from an external framework, then the framework is definitely not in the same target as the OBJECTIVE-C project, and we need to import the external Swift module. This is the same as using the original framework of OBJECTIVE-C, for a project, the external framework is written by Swift or Objective-c, the two are not much different. We introduced module by using the new @import introduced in 2013:

The Swift-written framework can then be used normally.

If you want to use the source files of Swift in the same project in Objective-c, you can directly import the auto-generated header file {product-module-name}-swift.h to complete. For example, if the target of the project is called MYAPP, we need to write it in the Objective-c file.

" myapp-swift.h "

But this is just the beginning of the story. Objective-c and Swift use two completely different mechanisms at the bottom, and the Objective-c object in Cocoa is run-time based, and it follows KVC (Key-value Coding, storing object information in a dictionary-like way) and dynamic Dispatch, which determines the specific implementation of the actual invocation when the call is run. And Swift, in pursuit of performance, will not be determined at runtime if there is no special need. In other words, a member or method of the Swift type is determined at compile time, and the runtime no longer needs to go through a lookup and can be used directly.

Obviously, the problem with this is that if we are going to use Objective-c's code or feature to invoke the pure Swift type, we will fail because we cannot find the required runtime information. It is also easy to solve, in the Swift type file, we can add the @objc modifier to the declaration of any place that needs to be exposed to objective-c (including classes, properties, methods, etc.). Note that this step only needs to be for those types that are not inherited from NSObject, and Swift will automatically add @objc to all non-private classes and members if you write the class with Swift that inherits from NSObject. This means that for a nsobject subclass, you just need to import the appropriate header file to use this class in Objective-c.

Another function of the @objc modifier is to focus on the new declaration method or the name of the variable for objective-c. While most of the time the auto-Convert method name is good enough (for example, it converts a method like Init (name:string) in Swift to-initwithname: (NSString *) name), but sometimes we expect Objective-c uses a different method name or class name in Swift, such as a class in Swift:

class my class {      func greeting (name: String) {          println (" Hello, \ (name)")      }  }   My class (). Greeting (" xiaoming " )

Objective-c cannot be invoked in Chinese, so we must use @objc to convert it to ASCII in order to access it in Objective-c:

@objc (MyClass)   class my class {      @objc (greeting:)      func Hello (name: String) {          println (" Hello, \ (name)" ) )      }  

We can call [[MyClass new] greeting:@ "Xiaoming" in objective-c (though it's not fun at all). Also, as mentioned above and in the Selector section, Swift does not automatically add @objc to a method or member that is marked private, even if it is a subclass of NSObject. If we need to use the dynamic nature of these content, we need to manually add @objc modifiers to them.

Adding a @objc modifier does not mean that the method or property will become dynamically distributed, and Swift may still optimize it for static invocation. If you need the same runtime attributes as the dynamic call in Objective-c, the modifier you need to use is the dynamic. In general, when doing app development should not be used, but in the display of some like dynamic replacement method or run time to decide to implement such "black magic", we need to use the dynamic modifier. In a later section of the KVO, we will also mention an example of using dynamic.

Swift's compatibility with Objective-c "Black Magic": @objc and dynamic

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.