Swift & the Objective-C Runtime

Runtime In Objective-C

https://www.raywenderlich.com/61318/video-tutorial-objective-c-runtime

Runtime In Swift

In short there are Dynamic and Static types of method call dispatching.

Static - the function address to be called is determined in the compilation time, so that expense of such call is similar to C-function calling. This mechanism is used for private methods or final classes methods call dispatching.

Dynamic dispatching is mechinism which allows to implement polymorphism concept of OOP - the function address to be called is determined in running time. Swift has two subtypes of it:

2.1. Obj-C - you already described in the question. This mechanism is used when object inherits from NSObject or calling method has @objc prefix.

2.2. Virtual table based (like in C++) - there is similar witness tables. What it does during method call dispatching is just single arithmetic operation - calculation of actual function address based on function offset in the base class witness table and the object class witness table location. So that's a relatively cheap operation comparing to Obj-C. It explains why "pure" Swift approximates to C++ performance.

If you don't mark you method with private keyword or your class is not final and same time you class is "pure" Swift (it does not inherit NSObject) then this virtual table based mechanism is used. It means that all the methods by default are virtual.

Associated Objects

You can't add stored properties to an existing classes via categories and extensions in Objective-C and Swift.

Objective-C associated objects come to the rescue again, by acting as the storage for computed properties.

extension UIViewController {
    private struct AssociatedKeys {
        static var descriptiveName = "nsh_DescriptiveName"
    }

    var descriptiveName: String? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.descriptiveName) as? String
        }

        set {
            if let newValue = newValue {
                objc_setAssociatedObject(
                    self,
                    &AssociatedKeys.descriptiveName,
                    newValue as NSString?,
                    .OBJC_ASSOCIATION_RETAIN_NONATOMIC
                )
            }
        }
    }
}

Method Swizzling

Method swizzling lets you swap the implementations of two methods, essentially overriding an existing method with your own while keeping the original around.

results matching ""

    No results matching ""