Swift interoperability: Writing Swift classes with the Objective-c feature (Swift version 2.0)-B

Source: Internet
Author: User

This section includes the following:

    • Class inheriting objective-c (inheriting from Objective-c Classes)

    • Adoption Protocol (adopting protocols)

    • Writing constructors and destructors (Writing initializers and Deinitializers)

    • Integrated Interface Builder (integrating with Interface builder)

    • Specify attribute properties (specifying property Attributes)

    • Implement core Data Managed object subclass (implementing core Data Managed object subclasses)

    • Using the Swift class name with the Objective-c API

Interoperability (interoperability) enables developers to define swift classes that incorporate Objective-c language features. When you write a Swift class, you can inherit not only the parent class written by the Objective-c language, but also the OBJECTIVE-C protocol and some other features of objective-c. This means that developers can create swift classes based on familiar, reliable classes, methods, and frameworks already available in objective-c, and optimize them in combination with the modern and more efficient language features that Swift offers.

Classes that inherit Objective-c

In Swift, a developer can define a subclass that inherits from classes written using Objective-c. The subclass is created by adding a colon (:) after the class name of Swift, followed by the Objective-c class name.

Import Uikitclass Myswiftviewcontroller:uiviewcontroller {//define class}

Developers can inherit all of the functionality from Objective-c's parent class. If the developer wants to overwrite a method in the parent class, don't forget to use the override keyword.

Nscoding protocol

The nscoding protocol requires a conforming type to implement the required constructor init (coder:). Classes that use the Nscoding protocol directly must implement this method. Subclasses of classes that use the Nscoding protocol, which have one or more custom constructors or properties without initialization values, must also implement this method. Xcode provides the following placeholder implementations to remind you of:

Required Init (coder Adecoder:nscoder) {fatalerror ("init (coder:) have not been implemented")}

For objects that are loaded from storyboards or archived to disk with Nsuserdefaults or Nskeyedarchiver classes, you must provide an implementation of a complete initialization program. However, when a type cannot be instantiated in this way, you may not need to implement the constructor.

Adoption Protocol

In Swift, developers can use protocols defined in OBJECTIVE-C. As with the Swift protocol, all OBJECTIVE-C protocols are written in a comma-separated list followed by the parent class name of the class (if it has a parent class).

Class Myswiftviewcontroller:uiviewcontroller, Uitableviewdelegate, Uitableviewdatasource {//define classes}

The OBJECTIVE-C agreement is consistent with the use of the Swift protocol. If developers want to reference the Uitableviewdelegate protocol in Swift code, they can use uitableviewdelegate directly (the reference ID in Objective-c is equivalent).

Because the namespaces for classes and protocols are unified in Swift, the NSObject protocol in Objective-c is remapped to Nsobjectprotocol in Swift.

Writing constructors and destructors

The Swift compiler ensures that at initialization time, the constructor does not allow any uninitialized properties in the class, which can increase the security and predictability of the code. In addition, unlike the Objective-c language, Swift does not provide a separate memory allocation method for developers to invoke. When you use the native Swift initialization method (even with the Objective-c Class), Swift translates the Objective-c initialization method into Swift's initialization method. For more information on how to implement a developer custom constructor, see the constructor.

When the developer wants to perform additional cleanup work before the class is freed, a destructor is required to replace the Dealloc method. Swift automatically invokes the destructor to perform the destructor before the instance is released. After Swift invokes the destructor of the subclass, the destructor of the parent class is called automatically. When a developer uses the Objective-c class or a swift class that inherits from the Objective-c class, Swift also automatically calls the Dealloc method in the class's parent class for the developer. For more information on how to implement a developer custom destructor, see [destructor].

Integrated Interface Builder

The Swift compiler contains attributes that enable the developer's Swift class to integrate some of the features of Interface Builder. Like Objective-c, you can use Outlets,actions and live rendering (live rendering) in Swift.

Using Outlets and action

Use Outlets and Action to connect source code and Interface Builder's UI objects. Using Outlets and Action in Swift, you need to insert the @iboutlet or @ibaction keyword before the attribute and method declarations. Declaring a Outlet collection is also using the @iboutlet property, which is specifying an array for the type.

When a developer declares a Outlet in Swift, the Swift compiler automatically converts the type to weak (weak), implicit (implicitly), unpackaged (unwrapped) Optional (objective-c It corresponds to the pointer type) data type and assigns it an initialized null value of nil. In fact, the compiler uses @iboutlet weak var name:type! = Nil to replace the @IBOutlet var name:type. The compiler converts the type to a weak (weak), implicit (implicitly), unpackaged (unwrapped) optional type, so the developer does not need to assign an initial value to the type in the constructor. When the developer initializes the object class from the storyboard (storyboard) or the Xib file, the defined Outlet and the objects are connected together, so the Outlet are implicit and unpackaged. Because the created outlets are generally weak, the default outlets is a weak type.

For example, the following Swift code declares a class that owns the Outlet, Outlet collection, and Action:

Class Myviewcontroller:uiviewcontroller {@IBOutlet var button:uibutton @IBOutlet var textfields:uitextfield[]    @IBAction func buttontapped (anyobject) {println ("button tapped!") }}

In the Buttontapped method, the message sender's information is not used, so the parameter name of the method can be omitted.

Live Rendering (Live rendering)

Developers can use @ibdesignable and @ibinspectable in Interface Builder to create a vivid, interactive, custom view (view). When a developer inherits UIView or NSView from defining a view, you can add @ibdesignable properties before the class declaration. When you add a custom view in Interface Builder (set in the custom view class in the monitor panel), Interface Builder renders your customized view on the canvas.

Note: Real-time rendering only for objects in the frame

You can also add the @ibinspectable property to a Type property that is compatible with user-defined run-time properties. This way, when developers add custom views to Interface Builder, they can edit the properties in the Monitor panel.

@IBDesignableclass Mycustomview:uiview {@IBInspectable var textcolor:uicolor @IBInspectable var Iconheight:cgflo AT/* ... */}

Indicates attribute properties

In Objective-c, properties typically have a set of attribute (Attributes) descriptions that indicate some additional information about the property. In Swift, developers can specify these characteristics of attributes in different ways.

Strongly typed and weakly typed

The properties in Swift are strongly typed by default. Use the weak keyword to decorate a property that indicates that its object is stored as a weak reference. The keyword can only decorate the optional object type. For more information, check out the features.

Read/write and read-only

In Swift, there are no ReadWrite and readonly features. When declaring a stored-type property, use let to decorate it as read-only, and use Var to modify it to be read/write. When declaring a computed property, provide it with a getter method that makes it read-only, and provides getter and setter methods to make it readable/writable. For more information, check the properties.

Copy

In Swift, the copy attribute of Objective-c is converted to the @nscopying property. Attributes of this class must comply with the Nscopying protocol. For more information, check out the features.

Implementing the Core Data Managed object subclass

Core Data provides a set of properties for basic storage and implementation of Nsmanagedobject subclasses. Add the @nsmanaged attribute to the core Data model before you manage the attribute or each attribute definition of the relationship for the object subclass. Similar to the @dynamic features inside the objective-c, the @NSManaged feature informs the Swift compiler that the storage and implementation of this property will be done at run time. However, unlike @dynamic, @NSManaged features are available only in Core Data support.

The Swift classes are namespace---they are confined to the compiled modules (most typically target). In order to use the Swift subclass of the Nsmanagedobject class with the Core Data model, the module name is prefixed to the class name in the class area of the model entity monitor.

Using the Swift class name with the Objective-c API

The Swift classes are named based on the modules they are compiled, even if they are using code from OBJECTIVE-C. Unlike Objective-c, all classes are part of the global namespace and must not have the same name, and Swift classes can eliminate ambiguity based on their existing modules. For example, the fully qualified name of the Swift class called DataManager in the Myframework framework is Myframework.datamanager. A swift application target is the module itself, so in an application called MyGreatApp, the fully qualified name of the Swift class called Observer is Mygreatapp.observer.

To save the Swift class used in the Objective-c code, the Swift class bursts into the OBJECTIVE-C runtime with their fully qualified name. Therefore, you must include the fully qualified name of the class when you use an API that represents a function for the Swift class's string. For example, when you create a document-based MAC app, you provide the name of the Nsdocument subclass in the app's info.plist. In swift, you must use the full name of the text class, including the name of the module derived from your application or frame. In the following example, the Nsclassfromstring method is used to retrieve a reference from a class represented by a string. In order to retrieve the Swift class, you need to use the fully qualified name, including the name of the app.

Let Mypersonclass:anyclass (nsclassfromstring ("Mygreatapp.person"))

Swift interoperability: Writing Swift classes with the Objective-c feature (Swift version 2.0)-B

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.