Objective-C Exercises
Time to practise! Each exercise has a starter program that compiles and prints a placeholder result, so you can see the expected format. Replace the TODO parts and compare with the "Expected" output. The playgrounds on this site show the saved output of the starter code, so to really run your solution, paste it into Xcode (a macOS Command Line Tool project) or a clang + GNUstep setup. Try for a few minutes before opening a solution.
| # | Exercise | Topics |
|---|---|---|
| 1 | FizzBuzz string | loops, NSMutableString |
| 2 | Word frequency | NSDictionary, sorting keys |
| 3 | Reverse the words | NSString, NSArray |
| 4 | Temperature class | properties, initializers, description |
| 5 | Sum category | categories, NSNumber |
| 6 | Shapes protocol | protocols, polymorphism |
| 7 | Multiplier factory | blocks, capture |
| 8 | Config parser | NSError ** |
| 9 | Fix the leak | weak, dealloc |
1. FizzBuzz string
Build one string with the numbers 1 to 15 separated by spaces, but write Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.
Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableString *out = [NSMutableString string];
for (int i = 1; i <= 15; i++) {
// TODO: append Fizz, Buzz, FizzBuzz or the number, separated by spaces
}
NSLog(@"%@", out.length ? out : @"(empty)");
}
return 0;
}(empty)
Show solution
for (int i = 1; i <= 15; i++) {
if (i > 1) [out appendString:@" "];
if (i % 15 == 0) [out appendString:@"FizzBuzz"];
else if (i % 3 == 0) [out appendString:@"Fizz"];
else if (i % 5 == 0) [out appendString:@"Buzz"];
else [out appendFormat:@"%d", i];
}2. Word frequency
Count how often each word occurs (ignore case) and print the words alphabetically as word: count.
Expected (after the text: line):
a: 2
cat: 2
dog: 1
saw: 1#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSString *text = @"A cat saw a Dog cat";
NSLog(@"text: %@", text);
NSMutableDictionary<NSString *, NSNumber *> *counts = [NSMutableDictionary dictionary];
// TODO: split the lowercased text and count each word
NSArray *keys = [counts.allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *word in keys) {
NSLog(@"%@: %@", word, counts[word]);
}
NSLog(@"%lu distinct words", (unsigned long)counts.count);
}
return 0;
}text: A cat saw a Dog cat
0 distinct words
Show solution
for (NSString *word in [[text lowercaseString] componentsSeparatedByString:@" "]) {
counts[word] = @(counts[word].integerValue + 1);
}Messaging nil returns 0, so a new word starts at 0 + 1.
3. Reverse the words
Write NSString *ReverseWords(NSString *sentence) that reverses the order of the words.
Expected: ReverseWords(@"objects send messages") returns messages send objects.
#import <Foundation/Foundation.h>
NSString *ReverseWords(NSString *sentence) {
// TODO: split, reverse, join
return sentence;
}
int main(void) {
@autoreleasepool {
NSLog(@"%@", ReverseWords(@"objects send messages"));
NSLog(@"%@", ReverseWords(@"single"));
}
return 0;
}objects send messages
single
Show solution
NSString *ReverseWords(NSString *sentence) {
NSArray *words = [sentence componentsSeparatedByString:@" "];
NSArray *reversed = [[words reverseObjectEnumerator] allObjects];
return [reversed componentsJoinedByString:@" "];
}4. Temperature class
Give Temperature an initializer initWithCelsius:, a read-only computed property fahrenheit, and a description that prints 21.5 C = 70.7 F.
#import <Foundation/Foundation.h>
@interface Temperature : NSObject
@property (nonatomic, readonly) double celsius;
@property (nonatomic, readonly) double fahrenheit;
- (instancetype)initWithCelsius:(double)celsius;
@end
@implementation Temperature
- (instancetype)initWithCelsius:(double)celsius {
self = [super init];
// TODO: store celsius
return self;
}
- (double)fahrenheit {
return 0; // TODO
}
- (NSString *)description {
return [NSString stringWithFormat:@"%.1f C = %.1f F", self.celsius, self.fahrenheit];
}
@end
int main(void) {
@autoreleasepool {
NSLog(@"%@", [[Temperature alloc] initWithCelsius:21.5]);
NSLog(@"%@", [[Temperature alloc] initWithCelsius:-40]);
}
return 0;
}0.0 C = 0.0 F
0.0 C = 0.0 F
Expected: 21.5 C = 70.7 F and -40.0 C = -40.0 F.
Show solution
- (instancetype)initWithCelsius:(double)celsius {
self = [super init];
if (self) {
_celsius = celsius;
}
return self;
}
- (double)fahrenheit {
return self.celsius * 9 / 5 + 32;
}5. Sum category
Add a category NSArray (Stats) with - (double)sum and - (double)average (0 for an empty array) for arrays of NSNumber.
Expected: sum 10.0, average 2.5 and empty: sum 0.0, average 0.0.
#import <Foundation/Foundation.h>
@interface NSArray (Stats)
- (double)sum;
- (double)average;
@end
@implementation NSArray (Stats)
- (double)sum {
return 0; // TODO
}
- (double)average {
return 0; // TODO
}
@end
int main(void) {
@autoreleasepool {
NSArray *values = @[@1, @2, @3, @4];
NSLog(@"sum %.1f, average %.1f", [values sum], [values average]);
NSLog(@"empty: sum %.1f, average %.1f", [@[] sum], [@[] average]);
}
return 0;
}sum 0.0, average 0.0
empty: sum 0.0, average 0.0
Show solution
- (double)sum {
double total = 0;
for (NSNumber *n in self) total += n.doubleValue;
return total;
}
- (double)average {
return self.count ? [self sum] / self.count : 0;
}A shorter alternative uses KVC: [[self valueForKeyPath:@"@sum.self"] doubleValue].
6. Shapes protocol
Make Square and Circle adopt the Shape protocol and implement area and name, so the loop prints each area and the total.
Expected:
square: 4.00
circle: 3.14
total: 7.14#import <Foundation/Foundation.h>
@protocol Shape <NSObject>
- (double)area;
- (NSString *)name;
@end
@interface Square : NSObject // TODO: adopt Shape
@property (nonatomic) double side;
@end
@implementation Square
@end
@interface Circle : NSObject // TODO: adopt Shape
@property (nonatomic) double radius;
@end
@implementation Circle
@end
int main(void) {
@autoreleasepool {
Square *sq = [Square new];
sq.side = 2;
Circle *c = [Circle new];
c.radius = 1;
double total = 0;
for (id shape in @[sq, c]) {
if ([shape conformsToProtocol:@protocol(Shape)]) {
id<Shape> s = shape;
NSLog(@"%@: %.2f", [s name], [s area]);
total += [s area];
} else {
NSLog(@"(%@ is not a Shape yet)", NSStringFromClass([shape class]));
}
}
NSLog(@"total: %.2f", total);
}
return 0;
}(Square is not a Shape yet)
(Circle is not a Shape yet)
total: 0.00
Show solution
@interface Square : NSObject <Shape>
@property (nonatomic) double side;
@end
@implementation Square
- (double)area { return self.side * self.side; }
- (NSString *)name { return @"square"; }
@end
@interface Circle : NSObject <Shape>
@property (nonatomic) double radius;
@end
@implementation Circle
- (double)area { return M_PI * self.radius * self.radius; }
- (NSString *)name { return @"circle"; }
@end7. Multiplier factory
Write MakeMultiplier(factor) returning a block that multiplies its argument by factor. Then use it to transform an array.
Expected: double 7 = 14, triple 7 = 21 and tripled: 3 6 9.
#import <Foundation/Foundation.h>
typedef NSInteger (^Transform)(NSInteger);
Transform MakeMultiplier(NSInteger factor) {
// TODO: return a block that captures factor
return ^NSInteger(NSInteger x) { return x; };
}
int main(void) {
@autoreleasepool {
Transform twice = MakeMultiplier(2);
Transform thrice = MakeMultiplier(3);
NSLog(@"double 7 = %ld, triple 7 = %ld", (long)twice(7), (long)thrice(7));
NSMutableArray *out = [NSMutableArray array];
for (NSNumber *n in @[@1, @2, @3]) {
[out addObject:@(thrice(n.integerValue))];
}
NSLog(@"tripled: %@", [out componentsJoinedByString:@" "]);
}
return 0;
}double 7 = 7, triple 7 = 7
tripled: 1 2 3
Show solution
Transform MakeMultiplier(NSInteger factor) {
return ^NSInteger(NSInteger x) {
return x * factor; // factor is captured by value
};
}8. Config parser
Implement ParseLine so that key=value lines return a one-entry dictionary, and lines without = or with an empty key return nil and an NSError (domain Config, code 1, description Missing '=' in line: … or code 2, Empty key in line: …).
Expected:
port -> 8080
error 1: Missing '=' in line: debug
error 2: Empty key in line: =oops#import <Foundation/Foundation.h>
NSDictionary *ParseLine(NSString *line, NSError **error) {
// TODO: find '=', validate, fill *error on failure
return nil;
}
int main(void) {
@autoreleasepool {
for (NSString *line in @[@"port=8080", @"debug", @"=oops"]) {
NSError *error = nil;
NSDictionary *entry = ParseLine(line, &error);
if (entry) {
NSString *key = entry.allKeys.firstObject;
NSLog(@"%@ -> %@", key, entry[key]);
} else {
NSLog(@"error %ld: %@", (long)error.code, error.localizedDescription ?: @"(not implemented)");
}
}
}
return 0;
}error 0: (not implemented)
error 0: (not implemented)
error 0: (not implemented)
Show solution
NSDictionary *ParseLine(NSString *line, NSError **error) {
NSRange eq = [line rangeOfString:@"="];
NSInteger code = 0;
NSString *message = nil;
if (eq.location == NSNotFound) {
code = 1;
message = [NSString stringWithFormat:@"Missing '=' in line: %@", line];
} else if (eq.location == 0) {
code = 2;
message = [NSString stringWithFormat:@"Empty key in line: %@", line];
}
if (message) {
if (error) {
*error = [NSError errorWithDomain:@"Config" code:code
userInfo:@{NSLocalizedDescriptionKey: message}];
}
return nil;
}
return @{[line substringToIndex:eq.location]: [line substringFromIndex:NSMaxRange(eq)]};
}9. Fix the leak
A Team owns its Members, and each member points back to its team. Right now neither is ever freed. Change one word so that both dealloc messages appear.
Expected:
Ada is in Core
Team Core freed
Member Ada freed
team released#import <Foundation/Foundation.h>
@class Team;
@interface Member : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) Team *team; // TODO: is strong right here?
@end
@interface Team : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray<Member *> *members;
@end
@implementation Member
- (void)dealloc { NSLog(@"Member %@ freed", _name); }
@end
@implementation Team
- (void)dealloc { NSLog(@"Team %@ freed", _name); }
@end
int main(void) {
@autoreleasepool {
Team *team = [Team new];
team.name = @"Core";
team.members = [NSMutableArray array];
@autoreleasepool {
Member *ada = [Member new];
ada.name = @"Ada";
ada.team = team;
[team.members addObject:ada];
NSLog(@"%@ is in %@", ada.name, ada.team.name);
}
team = nil;
NSLog(@"team released");
}
return 0;
}Ada is in Core
team released
Show solution
@property (nonatomic, weak) Team *team;The team owns its members, so the back-reference must be weak. When team = nil removes the last strong reference, the team is freed, which releases its members array and therefore Ada.
Test yourself
In exercise 2, why does @(counts[word].integerValue + 1) work for a word seen for the first time?
- Dictionaries start every key at 0
- counts[word] is nil, and messaging nil returns 0
- integerValue throws and is caught
- It doesn't: it crashes
In exercise 9, which property must be weak?
- Team.members
- Member.team
- Member.name
- Team.name