What are objective c runtime features?
Asked Answered
C

2

5

In a blog post I have just read:

'Swift allows us to extend classes from NSObject to get Objective-C runtime features for an object. It also allows us to annotate Swift methods with @objc to allow the methods to be used by the Objective-C runtime.'

I don't understand the term objective-C runtime features. Is it meaning that the code could be used in a objective-C project as well?

Chopfallen answered 7/3, 2017 at 7:22 Comment(1)
T
3

Quoting the apple docs

The Objective-C runtime is a runtime library that provides support for the dynamic properties of the Objective-C language, and as such is linked to by all Objective-C apps. Objective-C runtime library support functions are implemented in the shared library found at /usr/lib/libobjc.A.dylib.

That API is useful primarily for developing bridge layers between Objective-C and other languages, or for low-level debugging. You most likely don't need to use it.

Even when written without a single line of Objective-C code, every Swift app executes inside the Objective-C runtime, so that's why you can access it.

You can do things like swizzling

Tankage answered 7/3, 2017 at 7:55 Comment(0)
C
0

Objective-C Runtime

A lot of programming languages is ship with a kind of runtime/standard library which includes some core/base functionality

Objective-C Runtime is responsible for dynamism, memory management(allocation, reference counting...) and other language features. It is a layer between compiler and core libraries/frameworks.

Objective-C is dynamic language because shift focus from compile time to runtime:

  • Dynamic typing - figure out object's class in runtime. inheritance and other OOP principles
  • Dynamic binding - figure out invoked method in runtime. Message dispatch mechanism[About]
  • Dynamic loading - you are able to lazy-loading a new module in runtime.

Other features:

  • basic structures like class, object, variable, property, method
  • functions for working with these structures
    • Introspection - get/read info about class/object in runtime. For example instance variables, methods names, method arguments. class_getName
    • Reflection - modify its own structure and behavior. For example allocate new class, add variable, add method. class_addMethod
    • objc_msgSend - based on message dispatch
    • Swizzling - swap method realisation in runtime. method_exchangeImplementations. [Objective C], [Swift] swizzling example

Using [@objc vs dynamic] expose Swift's API for Objective-C and adds a dynamic behaviour for Swift code. It is useful when you need something which is not possible to do with usual swift approaches. Good examples are KVO, swizzling...

[KVO]

Objective-C vs Swift

Swift can use Objective-C Runtime library.

Swift has better performance(based on table dispatch) but Objective-C is more dynamic language

Curagh answered 18/2, 2021 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.