Objects & Messaging
The heart of Objective-C is messaging. Instead of "calling a method", you send a message to an object, and the object decides at run time which code to run. The syntax is square brackets:
[receiver message]
[receiver messageWithArgument:value]
[receiver messageWithFirst:a second:b]Sending messages
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *title = @"objective-c basics";
// A message without arguments
NSString *upper = [title uppercaseString];
// A message with one argument: the colon introduces it
BOOL starts = [title hasPrefix:@"objective"];
// A message with two arguments: each part of the name gets one
NSString *changed = [title stringByReplacingOccurrencesOfString:@"basics"
withString:@"messaging"];
NSLog(@"%@", upper);
NSLog(@"starts with 'objective'? %d", starts);
NSLog(@"%@", changed);
NSLog(@"length: %lu", (unsigned long)[title length]);
}
return 0;
}OBJECTIVE-C BASICS
starts with 'objective'? 1
objective-c messaging
length: 18
The method in the third message is named stringByReplacingOccurrencesOfString:withString:. Its name is split into labelled parts, one per argument, so the call reads almost like an English sentence. This selector name (the full name with colons) is how Objective-C identifies a method.
Nesting messages
A message expression has a value, so you can use it as the receiver or the argument of another message. Read nested brackets from the inside out:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *raw = @" Hello, Cocoa ";
NSString *clean = [[raw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
lowercaseString];
NSLog(@"[%@]", clean);
// Creating objects is messaging too: alloc, then init
NSMutableArray *list = [[NSMutableArray alloc] init];
[list addObject:@"first"];
[list addObject:[clean uppercaseString]];
NSLog(@"%lu items, last is %@", (unsigned long)[list count], [list lastObject]);
}
return 0;
}[hello, cocoa]
2 items, last is HELLO, COCOA
[[NSMutableArray alloc] init] is the standard two-step way to create an object: alloc (sent to the class) reserves memory, and init (sent to the new instance) sets it up. Many classes also offer convenience class methods such as [NSMutableArray array].
Dot syntax
For simple getters and setters (properties) you can use dot syntax. title.length is just shorthand for [title length]; the compiler turns it into the same message.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *word = @"framework";
NSLog(@"%lu == %lu", (unsigned long)word.length, (unsigned long)[word length]);
NSLog(@"%@", word.uppercaseString);
NSLog(@"%@", word.capitalizedString);
}
return 0;
}9 == 9
FRAMEWORK
Framework
Tip: Use dot syntax for properties (state such as
length,name,count) and brackets for actions (addObject:,removeAllObjects). Apple's style guides follow this convention.
Messaging nil is safe
A message sent to nil does nothing and returns zero (nil, 0, NO). Unlike Java or Swift, there is no crash. This is convenient but can hide bugs.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *missing = nil;
NSLog(@"length of nil: %lu", (unsigned long)[missing length]);
NSLog(@"uppercase of nil: %@", [missing uppercaseString]);
NSLog(@"hasPrefix on nil: %d", [missing hasPrefix:@"a"]);
if (!missing) {
NSLog(@"missing is nil");
}
}
return 0;
}length of nil: 0
uppercase of nil: (null)
hasPrefix on nil: 0
missing is nil
What "dynamic" means
When you write [obj doSomething], the compiler doesn't hard-wire a function call. At run time, the Objective-C runtime looks up doSomething in obj's class (and its superclasses) and runs the method it finds. If none exists, the object gets a chance to handle the message anyway, and otherwise an "unrecognized selector" exception is raised. This late binding makes features like delegates, categories and Key-Value Coding possible, and you will see them all later in the course.
| Term | Meaning |
|---|---|
| receiver | the object a message is sent to |
| selector | the name of the method, such as addObject: |
| method | the code that runs for a selector in a particular class |
id |
a pointer to any object, whose class is not known at compile time |
Test yourself
What is the selector name of [text stringByReplacingOccurrencesOfString:@"a" withString:@"b"]?
- stringByReplacingOccurrencesOfString
- stringByReplacingOccurrencesOfString:withString:
- replace:with:
- withString:
What happens when you send [nil length]?
- The program crashes
- An exception is thrown
- Nothing; it returns 0
- It returns -1
name.length is shorthand for…
- name->length
- [name length]
- length(name)
- name[length]