Students will build a simple journal app to practice MVC separation, protocols, master-detail interfaces, table views, and persistence.
Journal is an excellent app to practice basic Cocoa Touch principles and design patterns. Students are encouraged to repeat building Journal regularly until the principles and patterns are internalized and the student can build Journal without a guide.
Students who complete this project independently are able to:
- Understand basic model-view-controller design and implementation
- Create a custom model object with a memberwise initializer
- Understand, create, and use a shared instance
- Create a model object controller with create, read, update, and delete functions
- Implement the Equatable protocol
- Implement a master-detail interface
- Implement the
UITableViewDataSource
protocol - Understand and implement the
UITextFieldDelegate
protocol to dismiss the keyboard - Create relationship segues in Storyboards
- Understand, use, and implement the 'updateViews' pattern
- Implement 'prepare(for segue: UIStoryboardSegue, sender: Any?)' to configure destination view controllers
- Add data persistence using the Codable protocol and write data to a local file path (URL).
- Upon launch, decode the data returned from the local file path (URL) back into our custom model objects.
Create an Entry model class that will hold title, text, and timestamp properties for each entry.
- Add a new
Entry.swift
file and define a newEntry
class - Add properties for timestamp, title, and body text
- Add a memberwise initializer that takes parameters for each property
- Consider setting a default parameter value for timestamp.
Create a model object controller called EntryController
that will manage adding, reading, updating, and removing entries. We will follow the shared instance design pattern because we want one consistent source of truth for our entry objects that are held on the controller.
- Add a new
EntryController.swift
file and define a newEntryController
class inside. - Add an entries array property, and set its value to an empty array
- Create a
addEntryWith(title: ...)
function that takes in atitle
, andtext
, creates a new instance ofEntry
, and adds it to the entries array - Create a
remove(entry: Entry)
function that removes the entry from the entries array
- There is no 'removeObject' function on arrays. You will need to find the index of the object and then remove the object at that index.
- You will face a compiler error because we have not given the Entry class a way to find equal objects. You will resolve the error by implementing the Equatable protocol in the next step.
- Create an
update(entry: ...)
function that should take in an existing entry as a parameter, as well as the title and text strings to update the entry with - Create a
shared
property as a shared instance
- Review the syntax for creating shared instance properties
Implement the Equatable protocol for the Entry class. The Equatable protocol allows you to check for equality between two variables of a specific class. You may use the ObjectIdentifier() function on class types, but you may decide to manually check the values of the title, text, and timestamp properties.
- Add the Equatable protocol function to the top or bottom of your
Entry.swift
file - Return the result of a comparison between the
lhs
andrhs
parameters using ObjectIdentifier() or checking the property values on each parameter
- Implement the NSCoding protocol on the Entry class
- Create a Unit test that verifies NSCoding functionality by converting an instance to and from NSData
Uncomment any relevant tests for this part. Verify that required classes are members of the test targets.
- Verifies Entry memberwise initializer
- Verifies existence of 'shared' instance
- Verifies adding entries from EntryController
- Verifies removing entries from EntryController
Build a view that lists all journal entries. You will use a UITableViewController and implement the UITableViewDataSource functions.
The UITableViewController subclass template comes with a lot of boilerplate and commented code. For readability, please remove all unnecessary boilerplate from your code.
You will want this view to reload the table view each time it appears in order to display newly created entries.
- Add a UITableViewController as your root view controller in Main.storyboard and embed it into a UINavigationController
- Create an
EntryListTableViewController
file as a subclass of UITableViewController and set the class of your root view controller scene - Implement the UITableViewDataSource functions using the EntryController
entries
array
- Pay attention to your
reuseIdentifier
in the Storyboard scene and yourdequeueReusableCell(withIdentifier:for:)
function call
- Set up your cells to display the title of the entry
- Implement the UITableViewDataSource
tableView(_:commit:forRowAt:)
function to enable swipe to delete functionality - Add a UIBarButtonItem to the UINavigationBar with the plus symbol
- Select 'Add' in the System Item menu from the Identity Inspector to set the button as a plus symbol, these are system bar button items, and include localization and other benefits
Build a view that provides editing and view functionality for a single entry. You will use a UITextField to capture the title, a UITextView to capture the body, a UIBarButtonItem to save the new or updated entry, and a UIButton to clear the title and body text areas.
Your Detail View should follow the 'updateViews' pattern for updating the view elements with the details of a model object. To follow this pattern, the developer adds an 'updateViews' function that checks for a model object. The function updates the view with details from the model object.
- Add an
EntryDetailViewController
file as a subclass of UIViewController and an optionalentry
property to the class - Add a UIViewController scene to Main.storyboard and set the class to
EntryDetailViewController
- Add a UITextField for the entry's title text to the top of the scene, add an outlet to the class file called
titleTextField
, and set the delegate relationship (To set the delegate relationship control drag from the UITextField to the current view controller in the scene dock) - Implement the delegate function
textFieldShouldReturn
to resign first responder to dismiss the keyboard (Before you implement the delegate function be sure to adopt the UITextFieldDelegate protocol) - Add a UITextView for the entry's body text beneath the title text field and add an outlet to the class file
bodyTextView
. - Add a UIButton beneath the body text view and add an IBAction to the class file that clears the text in the titleTextField and bodyTextView.
- Add a UIBarButtonItem to the UINavigationBar as a
Save
System Item and add an IBAction to the class file calledsaveButtonTapped
(You may need to add a segue fromEntryListTableViewController
to see a UINavigationBar on the detail view, and a UINavigationItem to add the UIBarButtonItem to the UINavigationBar, this will be covered in the next section) - In the
saveButtonTapped
IBAction, check if the optionalentry
property holds an entry, if so, call theupdate(entry: ...)
function in theEntryController
to update the properties of the entry. If not, call theadd(entry: Entry)
function on theEntryController
. After adding a new entry, or updating the existing entry, dismiss the current view. - Add an
updateViews()
function that checks if the optionalentry
property holds an entry. If it does, implement the function to update all view elements that reflect details about the model objectentry
(in this case, the titleTextField and bodyTextView) - Update the
viewDidLoad()
function to callupdateViews()
You will add two separate segues from the List View to the Detail View. The segue from the plus button will tell the EntryDetailViewController that it should create a new entry. The segue from a selected cell will tell the EntryDetailViewController that it should display a previously created entry, and save any changes to the same.
- Add a 'show' segue from the Add button to the EntryDetailViewController scene and give the segue an identifier (When naming the identifier, consider that this segue will be used to add an entry)
- Add a 'show' segue from the table view cell to the EntryDetailViewController scene and give the segue an identifier (When naming the identifier, consider that this segue will be used to edit an entry)
- Add a
prepare(for segue: UIStoryboardSegue, sender: Any?)
function to the EntryListTableViewController - Implement the
prepare(for segue: UIStoryboardSegue, sender: Any?)
function. If the identifier is 'toShowEntry' we will pass the selected entry to the DetailViewController, which will call ourupdateViews()
function
- You will need to capture the selected entry by using the indexPath of the selected cell
- Remember that the
updateViews()
function will update the destination view controller with the entry details - Since we aren't passing an entry if the identifier is 'toAddEntry' we don't need to account for this in our
prepare(for segue: UIStoryboardSegue, sender: Any?)
- Implement UITableViewCellEditingStyles to enable swipe to delete entries on the List View
- Update Unit and UITests to verify delete functionality
Uncomment any relevant tests for this part. Verify that required classes are members of the test targets.
- Verifies User Interface for adding and editing an entry
You will use the Codable protocol to add basic data persistence to the Journal app. Once your model objects you want to save are encoded into Data, you will save this data to a local file on disk. To access this file you will need a URL pointing it.
Our EntryController
object is the source of truth for entries. We are now adding a layer of persistent storage, so we need to update our EntryController
to load entries from persistent storage upon initialization and save the entries to persistent storage when they are created/updated.
- Copy and paste this method into your project. Note that this method returns a URL. This is the URL for the file location where we will be saving our Data.
private func fileURL() -> URL {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let fileName = "journal.json"
let documentsDirectoryURL = urls[0].appendingPathComponent(fileName)
return documentsDirectoryURL
}
- Write a method called
saveToPersistentStorage()
that will save the current entries array to a file on disk. Implement this function to: - Create an instance of
JSONEncoder
- Call
encode(value: Encodable) throws
on your instance of the JSONEncoder, passing in the array of entries as an argument. You will need to assign the return of this function to a constant nameddata
. NOTE - The objects in the array need to beCodable
objects. You need to go back to your Entry class and adopt the Codable protocol. - You will also notice that this function throws. That means that if you call this function and it doesn't work the way it should, it will
throw
an error. Functions that throw need to be marked withtry
in front of the function call. You will also need to put this call inside of a do catch block andcatch
the error that might be thrown. Review the documentation if you need to learn about do catch blocks. - You will also need to call
data.write(to: URL)
This function asks for a URL. We can pass in thefileURL()
as an argument. This is the line of code that will actually write the data at the URL. Hint - This is also a throwing function. - Call
saveToPersistentStorage()
any time that the list of entries is modified
-
Write a method called
loadFromPersistentStorage()
that will load the current data from the file on disk where we saved our entries(data). Implement this function to: -
Create an instance of
JSONDecoder
-
Create a constant called
data
to hold the data that you will get back by callingData(contentsOf:)
. You will need to pass in thefileURL()
as an argument. (This is a throwing function) -
Call
decode(from:)
on your instance of the JSONDecoder. You will need to assign the return of this function to a constant namedentries
. This function takes in two arguments: a type[Entry].self
, and your instance of data. It will decode the data into an array of Entry. -
Now set self.entries to this array of entries.
-
Call the
loadFromPersistentStorage()
function when theEntryController
is initialized
Your app should now function properly. Run the app and test for bugs.
- Add support for multiple journals by adding a Journal object that holds entries, a Journal list view that displays Journals, and making the Entry list view display just the entries from the selected journal
- Add support for tags on journals, add functionality to select a tag to display a list of entries with that tag
Uncomment any relevant tests for this part. Verify that required classes are members of the test targets.
- Verifies persistence cycle
Please refer to CONTRIBUTING.md.
© DevMountain LLC, 2015. Unauthorized use and/or duplication of this material without express and written permission from DevMountain, LLC is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to DevMountain with appropriate and specific direction to the original content.