SoFunction
Updated on 2025-04-11

Use Objective-C to write classes and inherit Objective-C classes in Swift

Interoperability (interoperability) enables developers to define Swift classes that incorporate Objective-C language features. When writing Swift classes, you can not only inherit the parent class written in the Objective-C language, adopt the Objective-C protocol, but also take advantage of some other functions of Objective-C. This means that developers can create Swift classes based on familiar and reliable classes, methods and frameworks already in Objective-C, and optimize them in combination with the modern and more efficient language features provided by Swift.

Inheriting Objective-C classes

In Swift, developers can define a subclass that inherits from a class written in Objective-C. The way to create this subclass is to add a colon (:) to the Swift class name, followed by the colon and the Objective-C class name.

Copy the codeThe code is as follows:

// SWIFT
import UIKit

class MySwiftViewController: UIViewController {
// Define the class
}

Developers can inherit all functions from the parent class of Objective-C. If the developer wants to override the methods in the parent class, don't forget to use the override keyword.
Adopt the agreement

In Swift, developers can adopt the protocols defined in Objective-C. Like 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).

Copy the codeThe code is as follows:

// SWIFT
class MySwiftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// Define the class
}

The Objective-C protocol is consistent with the Swift protocol. If the developer wants to reference the UITableViewDelegate protocol in Swift code, you can directly use UITableViewDelegate (referring to id<UITableViewDelegate\> in Objective-C is equivalent).

Writing constructors and destructors

Swift's compiler ensures that the constructor does not allow any uninitialized properties in the class when initializing, which can increase the security and predictability of the code. In addition, unlike Objective-C language, Swift does not provide a separate memory allocation method for developers to call. When you use native Swift initialization methods (even in collaboration with Objective-C classes), Swift converts the Objective-C initialization methods to Swift's initialization methods. For more information on how to implement a developer custom constructor, please check it outConstructor

When a developer wants to perform additional cleaning work before the class is released, a destruction process needs to be performed instead of the dealloc method. Swift automatically calls the destructor to perform the destruction process before the instance is released. After Swift calls the destructor of the subclass, the destructor of the parent class will be automatically called. When developers use the Objective-C class or Swift class inherited from the Objective-C class, Swift will automatically call the dealloc method in the parent class of this class for developers. For more information on how to implement a developer custom destructor, please check it outDestructor

Integrate Interface Builder

The Swift compiler contains some properties, which enables the developer's Swift class to integrate some special features in Interface Builder. Like in Objective-C, you can use OutLets, actions and live rendering in Swift.

Using Outlets and Action

Use Outlets and Action to connect source code to Interface Builder's UI objects. To use Outlets and Action in Swift, you need to insert the @IBOutlet or @IBAction keyword before the property and method declaration. Declaring an Outlet collection also uses the @IBOutlet attribute, that is, specify an array for the type.

When the developer declares an Outlet in Swift, the Swift compiler will automatically convert the type into a weak, implicitly, unwrapped optional (the corresponding pointer type in Object-c) data type, and assign it an initialized null value nil. In fact, the compiler uses @IBOutlet weak var name: Type! = nil instead of @IBOutlet var name: Type. The compiler converts this type into weak, implicitly, unwrapped optional types, so developers don't need to assign an initial value to the type in the constructor. After the developer initializes the object class from the storyboard or xib file, the defined Outlets are connected with these objects, so these Outlets are implicit and unwrapped. Since the created outlets are generally weak relationships, the default outlets are weak types.

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

Copy the codeThe code is as follows:

// SWIFT
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

Developers can use @IBDesignable and @IBInspectable to create vivid, interactive custom views (views) in Interface Builder. When a developer inherits UIView or NSView to customize a view (view), he can add the @IBDesignable attribute before the class declaration. When you add a custom view to Interface Builder (set in the Custom View class in the Monitor Panel), Interface Builder renders your custom view on the canvas.

Note: Real-time rendering can only be performed for objects in the framework.

You can also add the @IBIspectable property to a type attribute that is compatible with user-defined runtime properties. This way, when the developer adds a custom view to the Interface Builder, these properties can be edited in the monitor panel.

Copy the codeThe code is as follows:

// SWIFT

@IBDesignable

class MyCustomView: UIView {
    @IBInspectable var textColor: UIColor
    @IBInspectable var iconHeight: CGFloat
    /* ... */
}

Indicate attribute characteristics

In Objective-C, attributes usually have a set of Attributes descriptions to indicate some additional information about the attribute. In Swift, developers can specify these properties of properties in different ways.

Strong and weak types

The properties in Swift are all strongly typed by default. Use the weak keyword to modify an attribute, which can indicate that its object is a weak reference when stored. This keyword can only modify the optional object type. For more information, please checkcharacteristic

Read/write and read-only

In Swift, there are no readwrite and readonly features. When a storage property is declared, use let to modify it as read-only; use var to modify it as readable/write. When a computed property is declared, it is provided with a getter method to make it read-only; it is provided with a getter method and a setter method to make it readable/write. For more information, please checkproperty

copy

In Swift, the copy attribute of Objective-C is converted to the @NSCopying property. This type of attribute must comply with the NSCopying protocol. For more information, please checkcharacteristic

Implementing Core Data Managed Object Subclass

Core Data provides a set of properties that basic storage and implement NSManagedObject subclasses. In the Core Data model, add the @NSmanaged attribute before each property definition of a property related to a subclass of a management object. Similar to the @dynamic feature in Objective-C, the @NSManaged feature informs the Swift compiler that the storage and implementation of this property will be completed at runtime. However, unlike @dynamic, the @NSManaged feature is only available in Core Data support.