Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Objects and Classes

Methods and Messages

Learn Objective-C method declaration syntax, multi-argument messages and named parameters, selectors, self and super, return values, and why messaging nil is safe.

Calling a method in Objective-C is called sending a message. The syntax is unusual if you come from C, Java or Python: square brackets, the receiver first, and argument names written into the method name. Once it clicks, code reads almost like English. This lesson covers declaring and calling methods with any number of arguments, selectors, self and super, return values and the special behaviour of nil.

Message syntax

OBJECTIVEC
[receiver message];
[receiver messageWithArgument:value];
[receiver firstPart:value1 secondPart:value2];

The receiver is an object (or a class, for class methods). Messages can be nested, innermost first:

OBJECTIVEC
NSString *name = [[person fullName] uppercaseString];

[[Person alloc] init] is exactly this pattern.

Declaring methods

OBJECTIVEC
- (return type)nameWithFirst:(type)arg1 second:(type)arg2;

Every part before a colon is a piece of the method name:

OBJECTIVEC
- (void)greet;
- (void)greetPerson:(NSString *)name;
- (NSString *)joinFirst:(NSString *)first withLast:(NSString *)last;
- (BOOL)moveToX:(double)x y:(double)y animated:(BOOL)animated;

Calling the last one reads clearly: [view moveToX:10 y:20 animated:YES]. The full name, the selector, is moveToX:y:animated:. Colons are part of the name. Two methods may share the first word if their selectors differ: setValue: and setValue:forKey: are different methods.

The implementation repeats the declaration with a body:

OBJECTIVEC
- (NSString *)joinFirst:(NSString *)first withLast:(NSString *)last {
    return [NSString stringWithFormat:@"%@ %@", first, last];
}

Naming conventions

  • A method that returns a value is named for it (name, count), not getName.
  • Methods that act start with a verb: addObject:, removeAllItems.
  • Name each parameter's role in the selector: insertObject:atIndex:.
  • Boolean getters use is or has: isEmpty, hasPrefix:.

Selectors

A selector is the unique run-time identifier of a method name, of type SEL:

OBJECTIVEC
SEL s = @selector(joinFirst:withLast:);
NSLog(@"%@", NSStringFromSelector(s));      // joinFirst:withLast:
if ([person respondsToSelector:@selector(greet)]) {
    [person greet];
}

respondsToSelector: lets you call optional methods safely. If you send a message the receiver does not implement, the program crashes with unrecognized selector sent to instance, an extremely common run-time error.

self and super

Inside an instance method, self is the object that received the message, and you can send messages to it:

OBJECTIVEC
- (void)greetTwice {
    [self greet];
    [self greet];
}

super sends a message to the superclass's implementation, which is how a subclass extends rather than replaces inherited behaviour:

OBJECTIVEC
- (NSString *)description {
    return [NSString stringWithFormat:@"<Person %@: %@>", _name, [super description]];
}

super is not an object; it tells the runtime to start the method search in the superclass.

Return values and ignoring them

A method returns what its declared type says. You may ignore a return value; some APIs mark results as important with NS_WARN_UNUSED_RESULT.

Returning multiple values: a struct, a collection, or out-parameters:

OBJECTIVEC
- (BOOL)parse:(NSString *)text into:(NSInteger *)result error:(NSError **)error;

Messages to nil

Messaging nil is legal and does nothing, returning nil, 0 or NO:

OBJECTIVEC
Person *nobody = nil;
[nobody greet];                       // no effect
NSInteger age = [nobody age];         // 0
NSString *n = [nobody name];          // nil

For methods returning a struct, the result is zero-filled on current platforms. This removes endless null checks, but it can hide mistakes: if a value is unexpectedly nil, nothing visibly fails. Use NSParameterAssert for required arguments and log suspicious nil results.

Message dispatch

At run time [obj greet] becomes a call like objc_msgSend(obj, @selector(greet)). The runtime follows the object's isa pointer to its class, searches the class's method table (with a fast cache), walks up superclasses on a miss, and finally invokes the matching function pointer. If nothing is found it offers dynamic method resolution and forwarding before raising the unrecognized-selector exception.

flowchart LR
  A["[obj greet]"] --> B["objc_msgSend(obj, greet)"]
  B --> C{"Method in obj's class?"}
  C -- yes --> D["Run the implementation"]
  C -- no --> E{"In the superclass?"}
  E -- yes --> D
  E -- no --> F["Resolve / forward / unrecognized selector"]

The runtime walks up the class chain until it finds a matching method.

Stand-in: nil-safe messaging with a dispatch function

This C model sends "messages" to objects through one function that checks for a null receiver (returning 0) and reports unknown selectors, as the runtime does.

C Stand-in (C): msg_send with nil receiver and unknown selector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: super walks up the chain

C Stand-in (C): method lookup climbing superclasses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Leaving out the argument label: the call must match the selector exactly.
  • Misspelling a method name. It builds with a warning and crashes at run time.
  • Forgetting that [obj method] with a nil obj silently does nothing.
  • Using dot syntax for non-property methods (see Properties).
  • Confusing super with a stored object.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the selector of - (void)moveToX:(double)x y:(double)y;?

    The selector is every name part with its colons: moveToX:y:.
  2. 2. What does [nilObject length] return?

    A message to nil returns zero for numeric return types.
  3. 3. What happens when an object receives a message it does not implement and cannot forward?

    At run time the app throws NSInvalidArgumentException: unrecognized selector sent to instance.
  4. 4. What does [super description] do inside a subclass method?

    super starts the method lookup in the superclass.

Summary

  • Messages are written [receiver selector:arg part:arg]; colons belong to the method name.
  • Declare instance methods with -, class methods with +.
  • self is the receiver; super starts lookup in the superclass.
  • respondsToSelector: guards optional calls; unknown messages crash at run time.
  • Messaging nil safely returns nil/0/NO.

Next: Properties