skip to content

Objective-C

Objective-C and its runtime: messages sent to possibly nil receivers, property attributes, MRC and ARC, categories, blocks and KVO. Interviewers ask because mature iOS codebases still run on it.

on this pageshow

explore

questions

6

In Objective-C, what happens when you send a message to a nil receiver, and what value does the message return?

level: juniorimportance: must knowfreq 75%

answer

  1. no crash, no method runs
  2. objc_msgSend looks at the receiver
  3. zero of the declared return type
  4. arguments are still evaluated
  5. a nil block call is not a message

basics

~20 s

Sending a message to nil does nothing: no method runs and nothing is raised. The expression yields nil for an object, 0 for a number, NO for a BOOL and a zero-filled struct, and its arguments are still evaluated.

solid answer

~40 s

Every `[receiver message]` compiles to a call to `objc_msgSend`, and when the receiver is `nil` no method is looked up or run. Apple's guide states the result: `nil` for object return types, `0` for numeric types, `NO` for `BOOL`, and a returned struct with every member zeroed. The arguments are evaluated first, because they are ordinary expressions passed to that call. The convenience is also the trap: `photoIDs.count == 0` is true for an empty array and for no array at all, and a `nil` delegate makes a callback vanish without a trace. Two things that look alike do crash: calling a `nil` block, which is a plain call rather than a message, and inserting `nil` into a collection, which raises `NSInvalidArgumentException`.

code

objective-c · 25 lines
objective-c
#import <Foundation/Foundation.h>

@interface PPPrintOrder : NSObject
@property (nonatomic, copy) NSString *title;
@property (nonatomic) NSInteger copies;
- (BOOL)isPaid;
@end

@implementation PPPrintOrder
- (BOOL)isPaid { return YES; }
@end

void PPShowOrder(PPPrintOrder *order, NSArray<NSString *> *photoIDs) {
    NSString *title = order.title;      // nil when order is nil
    NSInteger copies = order.copies;    // 0
    BOOL paid = [order isPaid];         // NO: the method never runs
    NSUInteger count = photoIDs.count;  // 0 for nil AND for an empty array

    if (photoIDs == nil) {
        NSLog(@"photos never loaded");
    } else if (count == 0) {
        NSLog(@"order has no photos");
    }
    NSLog(@"%@ x%ld paid=%d", title, (long)copies, paid);
}

go deeper

for a junior

Recall the rule and the table: no method runs, and the result is nil, 0, NO or a zeroed struct. Show it with a property read on a nil object.

for a middle

Explain that objc_msgSend checks the receiver before any lookup, that arguments are still evaluated, and why calling a nil block or inserting nil into a collection crashes anyway.

for a senior

Show the bugs it hides: empty versus missing data, silent delegate no-ops, zero prices. Say where you test the pointer explicitly and how respondsToSelector: covers optional methods.

for a principal

Weigh the convenience against silent failure: decide where a codebase relies on nil messaging and where it demands explicit nil checks, nullability annotations and logging.

## How a message is sent In Objective-C a method call is a **message**. The compiler turns `[order isPaid]` into a call to the runtime function `objc_msgSend`, passing the **receiver** (`order`), the **selector** (the method's name, `isPaid`) and any arguments. At run time `objc_msgSend` follows the receiver's `isa` pointer to its class, finds the implementation for that selector in the class's dispatch table (or a superclass's), and calls it. Apple's runtime guide notes that you never call `objc_msgSend` yourself; the compiler generates those calls. When the receiver is `nil`, there is no object, no `isa` and no class to search. The runtime does not crash and does not raise: the message simply has no effect, and the expression produces a zero value. ## What a message to nil returns Apple's *Programming with Objective-C* guide spells out the result by return type: | Declared return type | Value of `[nil message]` | |---|---| | Object (`id`, `NSString *`, ...) | `nil` | | Numeric (`NSInteger`, `NSUInteger`, `double`, ...) | `0` | | `BOOL` | `NO` | | A struct | every member initialized to zero | | `void` | nothing happens | Property syntax is message syntax underneath, so `order.title` on a `nil` order is `nil` and `order.copies` is `0`. A chain such as `order.customer.name.length` quietly yields `0` if any link is `nil`. One detail surprises people: the **arguments are still evaluated**. In `[order setCopies:[self nextCopyCount]]`, `nextCopyCount` runs even when `order` is `nil`, because arguments are computed before the call is made. ## Why the language works this way Nil messaging lets ordinary code skip defensive checks: - An optional collaborator can be messaged directly: `[self.delegate printJobDidFinish:self]` is harmless when nobody set a delegate. - Lazy or failed lookups can flow through a chain of calls without a check at every step. - Teardown code can message objects that were never created, such as a timer that was never started. ## Where it hides bugs The same rule turns some mistakes into silent wrong answers instead of crashes: - **Empty versus missing.** `photoIDs.count == 0` cannot tell a loaded, empty array from a `nil` one that never loaded. An empty-state screen can then appear when loading actually failed. - **Silent no-ops.** A delegate or observer that was never wired up produces no error; the callback just never happens, and the print preview never refreshes. - **Zero that looks valid.** `[order totalPrice]` returning `0.0` for a missing order can flow into a checkout total. - **`NO` that looks like an answer.** `[order isPaid]` says `NO` both for an unpaid order and for no order. - **Equality between two nils.** `[a.title isEqualToString:b.title]` is `NO` when both titles are `nil`, because the message goes to `nil`; two untitled orders never compare equal, while the pointer comparison `a.title == b.title` says they are. - **Late failure.** A `nil` that should never have existed travels through several calls before anything visibly goes wrong, so the crash or wrong value appears far from the line that produced the `nil`. ## What still crashes Several things that look like nil messaging are not messages at all: 1. **Calling a nil block.** `completion(YES)` when `completion` is `nil` is a call through a null pointer and crashes with a bad-access fault. Guard it: `if (completion) { completion(YES); }`. 2. **Putting nil into a collection.** `[photos addObject:nil]` on a real `NSMutableArray` is a message to a non-nil array with a `nil` argument; Foundation raises `NSInvalidArgumentException` because the object cannot be `nil`. Use `NSNull` when a placeholder is genuinely needed. 3. **A missing method on a real object.** A non-nil receiver whose class has no implementation for the selector goes through dynamic resolution and forwarding, then `doesNotRecognizeSelector:`, which raises with "unrecognized selector sent to instance". 4. **Dereferencing an instance variable through a nil pointer.** `obj->_ivar` is a C memory access, not a message, so a `nil` `obj` crashes. ## Checking for nil when it matters When `nil` carries meaning, test the pointer itself, `if (photoIDs == nil)` or `if (!photoIDs)`, before relying on what a message returns. Keep a separate loading state when "not loaded" and "empty" must look different on screen, and for an `@optional` delegate method, check `respondsToSelector:` as well, since nil messaging protects only against a missing delegate, not a missing method.

  • How does sending a message to nil differ from sending a message an object does not implement?
    A `nil` receiver short-circuits and returns zero. A real object without a matching method goes through the runtime's fallbacks: `resolveInstanceMethod:` may add an implementation, `forwardingTargetForSelector:` may hand the message to another object, and `forwardInvocation:` gets a last chance. NSObject's default ends in `doesNotRecognizeSelector:`, which raises `NSInvalidArgumentException` with "unrecognized selector sent to instance".
  • Why can `if (photoIDs.count == 0)` show an empty-state screen when loading actually failed?
    Because `count` sent to a `nil` array returns `0`, so the check cannot separate "loaded, nothing there" from "never loaded". Test the pointer first with `photoIDs == nil`, or keep an explicit loading or error state, and drive the failure screen from the error path rather than from a zero.
  • Why isn't nil messaging enough to call an @optional delegate method safely?
    It only covers a `nil` delegate. If the delegate exists but did not implement the optional method, the message raises "unrecognized selector". Guard the call with `[self.delegate respondsToSelector:@selector(printJobDidFinish:)]`; when the delegate is `nil`, that check itself returns `NO`, so one test covers both cases.

  • Messaging nil throws an exception, like a null pointer error.
  • A message to nil returns garbage, so every call needs a nil check.
  • The arguments of a message to nil are never evaluated.
  • Calling a nil completion block is safe because blocks are objects.
  • A zero count proves the array exists and is empty.
  • Adding nil to an NSMutableArray is silently ignored like any nil message.
open as a page

In Objective-C, which @property attributes do you give a delegate, an NSString, a completion block and an NSInteger, and why?

level: middleimportance: must knowfreq 75%

basics

~20 s

All four take nonatomic. The delegate is weak so it never retains its owner; the NSString and the block are copy, snapshotting a mutable string and moving the block off the stack; the NSInteger is assign, its default.

open as a page

In Objective-C, an upload controller's copied progress block updates _sentBytes and the controller never deallocates; why, and how do __weak and __strong fix it?

level: seniorimportance: must knowfreq 65%

basics

~20 s

Inside a block, _sentBytes means self->_sentBytes, so the block captures self strongly while self owns the block through its copy property: a cycle. Capture a __weak self, promote it to a __strong local inside the block, and return when it is nil.

open as a page

In Objective-C, what can a class extension add to a class that a category cannot, and what happens when two category methods share a name?

level: middleimportance: should knowfreq 55%

basics

~20 s

A class extension can add instance variables and synthesized properties, because it compiles with the class's own @implementation; a category adds methods but no storage. When category methods clash with each other or the class, which one runs is undefined.

open as a page

In Objective-C, what do retain, release and autorelease do under manual reference counting, and what does ARC change about them?

level: middleimportance: should knowfreq 55%

basics

~20 s

Under manual reference counting, retain takes ownership, release gives it up, and autorelease gives it up later, when the enclosing autorelease pool drains. ARC makes the compiler insert those calls from the same ownership rules and forbids writing them yourself.

open as a page

As lead of an iOS app whose Objective-C core now serves new Swift screens, which Objective-C header and compiler rules would you enforce to keep that core healthy?

level: principalimportance: should knowfreq 35%

basics

~20 s

Treat each public header as the contract: wrap it in NS_ASSUME_NONNULL_BEGIN and END, mark the real nullables, add element types and designated initializers, turn nullability and implicit-self warnings into errors, finish ARC conversion, and fence categories and swizzling.

open as a page