Sobes.tech
Middle

What happens if you pass a nil value as the target object?

sobes.tech AI

Answer from AI

If you pass nil as the target object when sending a message in Objective-C, the message is simply ignored. This will not cause the application to crash or throw an error. This is a feature of Objective-C called "nil politeness". However, if the method is supposed to return a value, primitive types will return 0, NO, or NULL, and objects will return nil. In Swift, calling a method on an optional object that contains nil will also succeed (optional chaining).

// Example in Swift
let myOptionalObject: SomeClass? = nil

// Using optional chaining
myOptionalObject?.someMethod() // This call will do nothing and will not cause an error

let result = myOptionalObject?.someMethodReturningValue() // result will be nil

// Example in Objective-C SomeClass *myObject = nil; [myObject someMethod]; // This call will do nothing and will not cause an error

id result = [myObject someMethodReturningObject]; // result will be nil int intResult = [myObject someMethodReturningInt]; // intResult will be 0 BOOL boolResult = [myObject someMethodReturningBOOL]; // boolResult will be NO

What happens if you pass a nil value as the target… - sobes.tech