Sobes.tech
Intern

What will happen if you access the object?

sobes.tech AI

Answer from AI

A message is sent to an object. If the object has a method with the corresponding name (selector), it will be executed. If not, a runtime error occurs (unrecognized selector sent to instance), unless the object implements message forwarding.

The message forwarding mechanism in Objective-C/Swift consists of several stages:

  1. Dynamic dispatch: The runtime searches for an implementation of the method (IMP) for the given selector in the class of the object and its superclasses.
  2. Dynamic method addition: If no implementation is found, the runtime calls +resolveInstanceMethod: (for instances) or +resolveClassMethod: (for classes) to allow the class to dynamically add a method implementation.
  3. Message forwarding: If the method is still not found or added, the runtime attempts to forward the message to another object by calling forwardingTargetForSelector: and then methodSignatureForSelector: and forwardInvocation:.

If none of these stages handle the message, an NSInvalidArgumentException exception is raised.

Example in Objective-C:

@implementation MyObject

- (void)myMethod {
    // Method implementation
    NSLog(@"myMethod called");
}

@end

// ...
MyObject *obj = [[MyObject alloc] init];
[obj myMethod]; // Sending message myMethod

Example in Swift (implicit):

class MySwiftObject {
    func mySwiftMethod() {
        // Method implementation
        print("mySwiftMethod called")
    }
}

let swiftObj = MySwiftObject()
swiftObj.mySwiftMethod() // Sending message mySwiftMethod (via default dynamic dispatch)

Accessing object properties in Swift by default uses static dispatch for let and var without @objc dynamic. However, if a property is marked as @objc dynamic, accessing it will also use dynamic dispatch, similar to sending messages in Objective-C.