Methods
A method declaration in Objective-C has three ingredients: whether it's an instance (-) or class (+) method, its return type in parentheses, and its name interleaved with the parameters.
- (void)moveToX:(double)x y:(double)y animated:(BOOL)animated;
// ^ ^ ^ ^ ^
// | return name part param type more name parts
// instance methodThe selector of this method is moveToX:y:animated:.
Declaring and calling methods
#import <Foundation/Foundation.h>
@interface Calculator : NSObject
- (double)add:(double)a to:(double)b;
- (double)multiply:(double)a by:(double)b;
- (NSString *)describeNumber:(NSInteger)n;
- (void)reset;
@end
@implementation Calculator
- (double)add:(double)a to:(double)b {
return a + b;
}
- (double)multiply:(double)a by:(double)b {
return a * b;
}
- (NSString *)describeNumber:(NSInteger)n {
return n % 2 == 0 ? @"even" : @"odd";
}
- (void)reset {
NSLog(@"calculator reset");
}
@end
int main(void) {
@autoreleasepool {
Calculator *calc = [Calculator new];
NSLog(@"%.1f", [calc add:2.5 to:4]);
NSLog(@"%.1f", [calc multiply:3 by:[calc add:1 to:1]]);
NSLog(@"7 is %@", [calc describeNumber:7]);
[calc reset];
}
return 0;
}6.5
6.0
7 is odd
calculator reset
Name the parts so that a call reads well: [calc add:2.5 to:4], [list insertObject:x atIndex:0]. The first part usually describes the first argument; later parts are labels for the others.
Class methods
A method starting with + is sent to the class itself, not to an instance. Class methods are used for factory methods ("make me a new one") and utilities that don't need an object's state.
#import <Foundation/Foundation.h>
@interface Temperature : NSObject
@property (nonatomic) double celsius;
+ (instancetype)temperatureWithFahrenheit:(double)f; // factory method
+ (double)absoluteZero; // utility
- (double)fahrenheit;
@end
@implementation Temperature
+ (instancetype)temperatureWithFahrenheit:(double)f {
Temperature *t = [[self alloc] init]; // self is the class here
t.celsius = (f - 32) * 5 / 9;
return t;
}
+ (double)absoluteZero {
return -273.15;
}
- (double)fahrenheit {
return self.celsius * 9 / 5 + 32;
}
@end
int main(void) {
@autoreleasepool {
Temperature *body = [Temperature temperatureWithFahrenheit:98.6];
NSLog(@"%.1f C", body.celsius);
NSLog(@"%.1f F", [body fahrenheit]);
NSLog(@"absolute zero: %.2f C", [Temperature absoluteZero]);
}
return 0;
}37.0 C
98.6 F
absolute zero: -273.15 C
Foundation is full of class factory methods: [NSString stringWithFormat:…], [NSArray arrayWithObjects:…], [NSNumber numberWithInt:…].
Private methods and helper order
Methods implemented in the @implementation but not declared in the @interface are effectively private: other files don't know they exist. Modern clang lets a method call another method of the same class regardless of where it appears in the file.
#import <Foundation/Foundation.h>
@interface PasswordChecker : NSObject
- (NSString *)strengthOf:(NSString *)password;
@end
@implementation PasswordChecker
- (NSString *)strengthOf:(NSString *)password {
NSInteger score = [self lengthScore:password] + [self digitScore:password];
if (score >= 2) {
return @"strong";
}
return score == 1 ? @"medium" : @"weak";
}
// Private helpers: not in the interface
- (NSInteger)lengthScore:(NSString *)password {
return password.length >= 10 ? 1 : 0;
}
- (NSInteger)digitScore:(NSString *)password {
NSRange digit = [password rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
return digit.location != NSNotFound ? 1 : 0;
}
@end
int main(void) {
@autoreleasepool {
PasswordChecker *checker = [PasswordChecker new];
for (NSString *pw in @[@"cat", @"cat1", @"correcthorse", @"correcthorse9"]) {
NSLog(@"%-14@ %@", pw, [checker strengthOf:pw]);
}
}
return 0;
}cat weak
cat1 medium
correcthorse medium
correcthorse9 strong
Note: Objective-C has no
privatekeyword for methods. A method that isn't declared publicly can still be called at run time if someone knows its selector; "private" here means "not advertised". Class extensions (a later lesson) are the usual place to declare private methods and properties.
No overloading
Two methods can't share the same selector with different parameter types, as they can in Java or C++. Instead, the name changes: numberWithInt:, numberWithDouble:, numberWithBool:. Different labels mean different selectors, so add:to: and add: can coexist.
| Declaration | Selector |
|---|---|
- (void)reset; |
reset |
- (void)addItem:(id)item; |
addItem: |
- (void)addItem:(id)item quantity:(NSInteger)q; |
addItem:quantity: |
+ (instancetype)itemNamed:(NSString *)name; |
itemNamed: (a class method) |
Test yourself
What is the selector of - (void)setWidth:(double)w height:(double)h;?
- setWidth
- setWidth:height:
- setWidth:(double)height:(double)
- setWidthHeight
What does a + in front of a method declaration mean?
- It's a public method
- It's a class method, sent to the class
- It returns a value
- It overrides a superclass method
Inside a class method + (instancetype)make, what is self?
- nil
- A new instance
- The class object
- The superclass