Objective-C Mini Project
In this project you'll build TaskBoard, a small task manager in the style of a real Cocoa model layer. It brings together most of the course: classes and initializers, properties, NS_ENUM, collections, sorting with descriptors, blocks, NSError, delegation and a category.
By the end, TaskBoard understands commands like these:
add 2 Write release notes
add 3 Fix login crash
done 2
list
saveThe playgrounds can't read keyboard input, so the "user" is an array of command strings. In a real command-line tool you'd read lines from standard input; in an iOS app the same model classes would sit behind a table view.
Step 1: The task model
A task has an identifier, a title, a priority and a done flag. The identifier and title never change after creation, so they're readonly and set by the designated initializer. Priorities are an NS_ENUM.
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, TaskPriority) {
TaskPriorityLow = 1,
TaskPriorityMedium = 2,
TaskPriorityHigh = 3,
};
NSString *PriorityName(TaskPriority p) {
switch (p) {
case TaskPriorityLow: return @"low";
case TaskPriorityMedium: return @"medium";
case TaskPriorityHigh: return @"high";
}
return @"?";
}
@interface TaskItem : NSObject
@property (nonatomic, readonly) NSInteger identifier;
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic) TaskPriority priority;
@property (nonatomic, getter=isDone) BOOL done;
- (instancetype)initWithIdentifier:(NSInteger)identifier title:(NSString *)title
priority:(TaskPriority)priority NS_DESIGNATED_INITIALIZER;
- (instancetype)init __attribute__((unavailable("use initWithIdentifier:title:priority:")));
@end
@implementation TaskItem
- (instancetype)initWithIdentifier:(NSInteger)identifier title:(NSString *)title
priority:(TaskPriority)priority {
self = [super init];
if (self) {
_identifier = identifier;
_title = [title copy];
_priority = priority;
}
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"#%ld [%@] %-24@ (%@)", (long)self.identifier,
self.isDone ? @"x" : @" ", self.title, PriorityName(self.priority)];
}
@end
int main(void) {
@autoreleasepool {
TaskItem *a = [[TaskItem alloc] initWithIdentifier:1 title:@"Write release notes" priority:TaskPriorityMedium];
TaskItem *b = [[TaskItem alloc] initWithIdentifier:2 title:@"Fix login crash" priority:TaskPriorityHigh];
b.done = YES;
NSLog(@"%@", a);
NSLog(@"%@", b);
}
return 0;
}#1 [ ] Write release notes (medium)
#2 [x] Fix login crash (high)
%-24@ pads the title to 24 characters, so the priorities line up.
Step 2: The board, with NSError
TaskBoard owns the tasks. It keeps a private NSMutableArray and hands out immutable copies. Operations that can fail for reasons outside the programmer's control (an empty title, an unknown id) use the NSError ** pattern.
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, TaskPriority) { TaskPriorityLow = 1, TaskPriorityMedium, TaskPriorityHigh };
static NSString * const TaskBoardErrorDomain = @"TaskBoard";
typedef NS_ENUM(NSInteger, TaskBoardError) {
TaskBoardErrorEmptyTitle = 1,
TaskBoardErrorNotFound = 2,
};
@interface TaskItem : NSObject
@property (nonatomic, readonly) NSInteger identifier;
@property (nonatomic, copy, readonly) NSString *title;
@property (nonatomic) TaskPriority priority;
@property (nonatomic, getter=isDone) BOOL done;
- (instancetype)initWithIdentifier:(NSInteger)identifier title:(NSString *)title priority:(TaskPriority)priority;
@end
@implementation TaskItem
- (instancetype)initWithIdentifier:(NSInteger)identifier title:(NSString *)title priority:(TaskPriority)priority {
self = [super init];
if (self) { _identifier = identifier; _title = [title copy]; _priority = priority; }
return self;
}
@end
@interface TaskBoard : NSObject
@property (nonatomic, readonly) NSArray<TaskItem *> *tasks;
- (TaskItem *)addTaskWithTitle:(NSString *)title priority:(TaskPriority)priority error:(NSError **)error;
- (BOOL)completeTaskWithIdentifier:(NSInteger)identifier error:(NSError **)error;
@end
@interface TaskBoard ()
@property (nonatomic, strong) NSMutableArray<TaskItem *> *storage;
@property (nonatomic) NSInteger nextIdentifier;
@end
@implementation TaskBoard
- (instancetype)init {
self = [super init];
if (self) {
_storage = [NSMutableArray array];
_nextIdentifier = 1;
}
return self;
}
- (NSArray<TaskItem *> *)tasks {
return [self.storage copy];
}
static NSError *MakeError(TaskBoardError code, NSString *message) {
return [NSError errorWithDomain:TaskBoardErrorDomain code:code
userInfo:@{NSLocalizedDescriptionKey: message}];
}
- (TaskItem *)addTaskWithTitle:(NSString *)title priority:(TaskPriority)priority error:(NSError **)error {
NSString *clean = [title stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if (clean.length == 0) {
if (error) *error = MakeError(TaskBoardErrorEmptyTitle, @"A task needs a title.");
return nil;
}
TaskItem *task = [[TaskItem alloc] initWithIdentifier:self.nextIdentifier++ title:clean priority:priority];
[self.storage addObject:task];
return task;
}
- (BOOL)completeTaskWithIdentifier:(NSInteger)identifier error:(NSError **)error {
for (TaskItem *task in self.storage) {
if (task.identifier == identifier) {
task.done = YES;
return YES;
}
}
if (error) {
*error = MakeError(TaskBoardErrorNotFound,
[NSString stringWithFormat:@"There is no task #%ld.", (long)identifier]);
}
return NO;
}
@end
int main(void) {
@autoreleasepool {
TaskBoard *board = [TaskBoard new];
NSError *error = nil;
[board addTaskWithTitle:@"Write release notes" priority:TaskPriorityMedium error:&error];
[board addTaskWithTitle:@"Fix login crash" priority:TaskPriorityHigh error:&error];
if (![board addTaskWithTitle:@" " priority:TaskPriorityLow error:&error]) {
NSLog(@"add failed: %@", error.localizedDescription);
}
[board completeTaskWithIdentifier:2 error:NULL];
if (![board completeTaskWithIdentifier:9 error:&error]) {
NSLog(@"complete failed (code %ld): %@", (long)error.code, error.localizedDescription);
}
for (TaskItem *t in board.tasks) {
NSLog(@"#%ld %@ %@", (long)t.identifier, t.title, t.isDone ? @"(done)" : @"");
}
}
return 0;
}add failed: A task needs a title.
complete failed (code 2): There is no task #9.
#1 Write release notes
#2 Fix login crash (done)
Notice the class extension @interface TaskBoard (): from outside, tasks is a read-only snapshot; inside, the board works with its private mutable storage.
Step 3: Sorting, filtering and statistics
Views of the board are computed on demand: open tasks sorted by priority (highest first) and then by id, using sort descriptors; filtering with a block; and counts with KVC collection operators. A category on NSArray adds a reusable filter helper.
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, TaskPriority) { TaskPriorityLow = 1, TaskPriorityMedium, TaskPriorityHigh };
@interface TaskItem : NSObject
@property (nonatomic) NSInteger identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic) TaskPriority priority;
@property (nonatomic, getter=isDone) BOOL done;
+ (instancetype)task:(NSInteger)i title:(NSString *)t priority:(TaskPriority)p done:(BOOL)d;
@end
@implementation TaskItem
+ (instancetype)task:(NSInteger)i title:(NSString *)t priority:(TaskPriority)p done:(BOOL)d {
TaskItem *task = [self new];
task.identifier = i; task.title = t; task.priority = p; task.done = d;
return task;
}
@end
@interface NSArray (TaskFiltering)
- (NSArray *)tb_filteredWith:(BOOL (^)(id obj))test;
@end
@implementation NSArray (TaskFiltering)
- (NSArray *)tb_filteredWith:(BOOL (^)(id))test {
NSIndexSet *hits = [self indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return test(obj);
}];
return [self objectsAtIndexes:hits];
}
@end
NSArray *OpenTasksByUrgency(NSArray *tasks) {
NSArray *open = [tasks tb_filteredWith:^BOOL(TaskItem *t) { return !t.isDone; }];
NSSortDescriptor *byPriority = [NSSortDescriptor sortDescriptorWithKey:@"priority" ascending:NO];
NSSortDescriptor *byId = [NSSortDescriptor sortDescriptorWithKey:@"identifier" ascending:YES];
return [open sortedArrayUsingDescriptors:@[byPriority, byId]];
}
int main(void) {
@autoreleasepool {
NSArray *tasks = @[[TaskItem task:1 title:@"Write release notes" priority:TaskPriorityMedium done:NO],
[TaskItem task:2 title:@"Fix login crash" priority:TaskPriorityHigh done:YES],
[TaskItem task:3 title:@"Update icons" priority:TaskPriorityLow done:NO],
[TaskItem task:4 title:@"Review pull request" priority:TaskPriorityHigh done:NO],
[TaskItem task:5 title:@"Plan sprint" priority:TaskPriorityMedium done:NO]];
for (TaskItem *t in OpenTasksByUrgency(tasks)) {
NSLog(@"P%ld #%ld %@", (long)t.priority, (long)t.identifier, t.title);
}
NSArray *done = [tasks tb_filteredWith:^BOOL(TaskItem *t) { return t.isDone; }];
NSLog(@"%lu of %@ done", (unsigned long)done.count, [tasks valueForKeyPath:@"@count"]);
NSLog(@"highest priority: %@", [tasks valueForKeyPath:@"@max.priority"]);
NSLog(@"titles: %@", [[tasks valueForKey:@"title"] componentsJoinedByString:@" | "]);
}
return 0;
}P3 #4 Review pull request
P2 #1 Write release notes
P2 #5 Plan sprint
P1 #3 Update icons
1 of 5 done
highest priority: 3
titles: Write release notes | Fix login crash | Update icons | Review pull request | Plan sprint
The category method has a tb_ prefix, as recommended for categories on system classes.
Step 4: Telling others about changes
The board shouldn't know who displays it. A delegate protocol reports changes, and the delegate is weak. A summary printer acts as the delegate here; in an app, it would be a view controller refreshing a table.
#import <Foundation/Foundation.h>
@class TaskBoard;
@interface TaskItem : NSObject
@property (nonatomic) NSInteger identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, getter=isDone) BOOL done;
@end
@implementation TaskItem
@end
@protocol TaskBoardDelegate <NSObject>
- (void)taskBoard:(TaskBoard *)board didAddTask:(TaskItem *)task;
@optional
- (void)taskBoard:(TaskBoard *)board didCompleteTask:(TaskItem *)task;
@end
@interface TaskBoard : NSObject
@property (nonatomic, weak) id<TaskBoardDelegate> delegate;
@property (nonatomic, readonly) NSUInteger openCount;
- (void)add:(NSString *)title;
- (void)complete:(NSInteger)identifier;
@end
@implementation TaskBoard {
NSMutableArray<TaskItem *> *_tasks;
}
- (instancetype)init {
self = [super init];
if (self) { _tasks = [NSMutableArray array]; }
return self;
}
- (NSUInteger)openCount {
NSUInteger n = 0;
for (TaskItem *t in _tasks) if (!t.isDone) n++;
return n;
}
- (void)add:(NSString *)title {
TaskItem *t = [TaskItem new];
t.identifier = _tasks.count + 1;
t.title = title;
[_tasks addObject:t];
[self.delegate taskBoard:self didAddTask:t];
}
- (void)complete:(NSInteger)identifier {
for (TaskItem *t in _tasks) {
if (t.identifier == identifier && !t.isDone) {
t.done = YES;
if ([self.delegate respondsToSelector:@selector(taskBoard:didCompleteTask:)]) {
[self.delegate taskBoard:self didCompleteTask:t];
}
}
}
}
@end
@interface SummaryPrinter : NSObject <TaskBoardDelegate>
@end
@implementation SummaryPrinter
- (void)taskBoard:(TaskBoard *)board didAddTask:(TaskItem *)task {
NSLog(@"+ #%ld %@ (%lu open)", (long)task.identifier, task.title, (unsigned long)board.openCount);
}
- (void)taskBoard:(TaskBoard *)board didCompleteTask:(TaskItem *)task {
NSLog(@"✓ #%ld %@ (%lu open)", (long)task.identifier, task.title, (unsigned long)board.openCount);
}
@end
int main(void) {
@autoreleasepool {
TaskBoard *board = [TaskBoard new];
SummaryPrinter *printer = [SummaryPrinter new];
board.delegate = printer;
[board add:@"Write release notes"];
[board add:@"Fix login crash"];
[board complete:2];
[board complete:2]; // already done: no second message
[board add:@"Plan sprint"];
}
return 0;
}+ #1 Write release notes (1 open)
+ #2 Fix login crash (2 open)
✓ #2 Fix login crash (1 open)
+ #3 Plan sprint (2 open)
Step 5: The command processor
Finally, everything comes together. A CommandProcessor parses each command line, calls the board, and turns every NSError into a friendly message. Its save command exports the board as simple tab-separated text, and load reads it back, a format you could write to a file with writeToFile:atomically:encoding:error: on a Mac.
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, TaskPriority) { TaskPriorityLow = 1, TaskPriorityMedium, TaskPriorityHigh };
@interface TaskItem : NSObject
@property (nonatomic) NSInteger identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic) TaskPriority priority;
@property (nonatomic, getter=isDone) BOOL done;
@end
@implementation TaskItem
@end
@interface TaskBoard : NSObject
@property (nonatomic, readonly) NSArray<TaskItem *> *tasks;
- (TaskItem *)addTitle:(NSString *)title priority:(TaskPriority)priority error:(NSError **)error;
- (BOOL)complete:(NSInteger)identifier error:(NSError **)error;
- (NSString *)exportText;
- (BOOL)importText:(NSString *)text error:(NSError **)error;
@end
@implementation TaskBoard {
NSMutableArray<TaskItem *> *_tasks;
NSInteger _nextId;
}
- (instancetype)init {
self = [super init];
if (self) { _tasks = [NSMutableArray array]; _nextId = 1; }
return self;
}
- (NSArray<TaskItem *> *)tasks { return [_tasks copy]; }
static NSError *BoardError(NSInteger code, NSString *msg) {
return [NSError errorWithDomain:@"TaskBoard" code:code userInfo:@{NSLocalizedDescriptionKey: msg}];
}
- (TaskItem *)addTitle:(NSString *)title priority:(TaskPriority)priority error:(NSError **)error {
if (title.length == 0) {
if (error) *error = BoardError(1, @"a task needs a title");
return nil;
}
if (priority < TaskPriorityLow || priority > TaskPriorityHigh) {
if (error) *error = BoardError(3, [NSString stringWithFormat:@"priority must be 1-3, got %ld", (long)priority]);
return nil;
}
TaskItem *t = [TaskItem new];
t.identifier = _nextId++;
t.title = title;
t.priority = priority;
[_tasks addObject:t];
return t;
}
- (BOOL)complete:(NSInteger)identifier error:(NSError **)error {
for (TaskItem *t in _tasks) {
if (t.identifier == identifier) { t.done = YES; return YES; }
}
if (error) *error = BoardError(2, [NSString stringWithFormat:@"no task #%ld", (long)identifier]);
return NO;
}
- (NSString *)exportText {
NSMutableArray *lines = [NSMutableArray array];
for (TaskItem *t in _tasks) {
[lines addObject:[NSString stringWithFormat:@"%ld\t%ld\t%d\t%@",
(long)t.identifier, (long)t.priority, t.isDone, t.title]];
}
return [lines componentsJoinedByString:@"\n"];
}
- (BOOL)importText:(NSString *)text error:(NSError **)error {
NSMutableArray *loaded = [NSMutableArray array];
NSInteger maxId = 0;
for (NSString *line in [text componentsSeparatedByString:@"\n"]) {
NSArray *f = [line componentsSeparatedByString:@"\t"];
if (f.count != 4) {
if (error) *error = BoardError(4, [NSString stringWithFormat:@"bad line with %lu field(s)", (unsigned long)f.count]);
return NO; // nothing is changed on failure
}
TaskItem *t = [TaskItem new];
t.identifier = [f[0] integerValue];
t.priority = [f[1] integerValue];
t.done = [f[2] boolValue];
t.title = f[3];
[loaded addObject:t];
maxId = MAX(maxId, t.identifier);
}
_tasks = loaded;
_nextId = maxId + 1;
return YES;
}
@end
@interface CommandProcessor : NSObject
- (instancetype)initWithBoard:(TaskBoard *)board;
- (void)run:(NSString *)line;
@end
@implementation CommandProcessor {
TaskBoard *_board;
NSString *_saved;
}
- (instancetype)initWithBoard:(TaskBoard *)board {
self = [super init];
if (self) { _board = board; }
return self;
}
- (void)run:(NSString *)line {
NSLog(@"> %@", line);
NSArray *words = [line componentsSeparatedByString:@" "];
NSString *cmd = words.firstObject;
NSError *error = nil;
BOOL ok = YES;
if ([cmd isEqualToString:@"add"] && words.count >= 2) {
NSInteger priority = [words[1] integerValue];
NSString *title = [[words subarrayWithRange:NSMakeRange(2, words.count - 2)] componentsJoinedByString:@" "];
TaskItem *t = [_board addTitle:title priority:priority error:&error];
ok = t != nil;
if (ok) NSLog(@" added #%ld", (long)t.identifier);
} else if ([cmd isEqualToString:@"done"] && words.count == 2) {
ok = [_board complete:[words[1] integerValue] error:&error];
if (ok) NSLog(@" completed #%@", words[1]);
} else if ([cmd isEqualToString:@"list"]) {
NSSortDescriptor *open = [NSSortDescriptor sortDescriptorWithKey:@"done" ascending:YES];
NSSortDescriptor *prio = [NSSortDescriptor sortDescriptorWithKey:@"priority" ascending:NO];
for (TaskItem *t in [_board.tasks sortedArrayUsingDescriptors:@[open, prio]]) {
NSLog(@" [%@] P%ld #%ld %@", t.isDone ? @"x" : @" ", (long)t.priority, (long)t.identifier, t.title);
}
} else if ([cmd isEqualToString:@"save"]) {
_saved = [_board exportText];
NSLog(@" saved %lu task(s), %lu characters", (unsigned long)_board.tasks.count, (unsigned long)_saved.length);
} else if ([cmd isEqualToString:@"load"]) {
NSString *source = words.count > 1 ? @"1\t2\t0" : _saved; // "load broken" simulates a corrupt file
ok = [_board importText:source error:&error];
if (ok) NSLog(@" loaded %lu task(s)", (unsigned long)_board.tasks.count);
} else {
NSLog(@" unknown command '%@'", cmd);
}
if (!ok) {
NSLog(@" error %ld: %@", (long)error.code, error.localizedDescription);
}
}
@end
int main(void) {
@autoreleasepool {
CommandProcessor *cli = [[CommandProcessor alloc] initWithBoard:[TaskBoard new]];
NSArray *session = @[@"add 2 Write release notes",
@"add 3 Fix login crash",
@"add 1 Update icons",
@"add 7 Celebrate",
@"done 2",
@"done 42",
@"list",
@"save",
@"done 1",
@"load broken",
@"load",
@"list",
@"undo"];
for (NSString *line in session) {
[cli run:line];
}
}
return 0;
}> add 2 Write release notes
added #1
> add 3 Fix login crash
added #2
> add 1 Update icons
added #3
> add 7 Celebrate
error 3: priority must be 1-3, got 7
> done 2
completed #2
> done 42
error 2: no task #42
> list
[ ] P2 #1 Write release notes
[ ] P1 #3 Update icons
[x] P3 #2 Fix login crash
> save
saved 3 task(s), 66 characters
> done 1
completed #1
> load broken
error 4: bad line with 3 field(s)
> load
loaded 3 task(s)
> list
[ ] P2 #1 Write release notes
[ ] P1 #3 Update icons
[x] P3 #2 Fix login crash
> undo
unknown command 'undo'
Look closely at the end of the session: after save, task #1 was completed, then load broken failed without changing anything (the import builds a new array and only replaces the old one on success), and load restored the saved state in which #1 is open again.
Ideas to extend TaskBoard
- Add a
rename <id> <title>command.titleisreadonlyin step 1: how would you allow renaming without making it publicly writable? - Post an
NSNotificationnamedTaskBoardDidChangeNotificationafter every change, and register two observers. - Add due dates with
NSDateand sort overdue tasks first (use fixed dates so the output stays deterministic). - Write an
undocommand: keep a stack of exported snapshots and restore the previous one. - Turn the model into a macOS app: an
NSTableViewdata source asks the board fortasks.countand the task at each row.
Test yourself
Why does importText:error: build a separate loaded array before replacing _tasks?
- For speed
- So a failed import leaves the existing tasks unchanged
- Because NSMutableArray can't be cleared
- To avoid a retain cycle
In step 4, why is the board's delegate property weak?
- Protocols require weak
- The delegate usually owns the board, so strong would form a cycle
- Weak properties are faster
- So it can be nil
Why is the category method called tb_filteredWith: instead of filteredWith:?
- Categories require a prefix
- To avoid clashing with methods other code or Apple might add to NSArray
- The compiler rejects unprefixed names
- It makes the method private