<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: OLAWOYE OMOTAYO</title>
    <description>The latest articles on Forem by OLAWOYE OMOTAYO (@omotayodavid).</description>
    <link>https://forem.com/omotayodavid</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F686305%2F9df7b45d-8c03-4f84-ba66-339329ab61af.jpeg</url>
      <title>Forem: OLAWOYE OMOTAYO</title>
      <link>https://forem.com/omotayodavid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/omotayodavid"/>
    <language>en</language>
    <item>
      <title>Create a Note App with Swift and Core Data - II</title>
      <dc:creator>OLAWOYE OMOTAYO</dc:creator>
      <pubDate>Thu, 12 May 2022 18:14:08 +0000</pubDate>
      <link>https://forem.com/omotayodavid/create-a-note-app-with-swift-and-core-data-ii-28el</link>
      <guid>https://forem.com/omotayodavid/create-a-note-app-with-swift-and-core-data-ii-28el</guid>
      <description>&lt;p&gt;In the &lt;a href="https://dev.to/omotayodavid/create-a-note-app-with-swift-and-core-data-h2p"&gt;first part of this article&lt;/a&gt;, we were able to design the UI for our Note App and also implemented the Create and Read operations of our app.&lt;/p&gt;

&lt;p&gt;Let's take it a step further by implementing the Update and Delete operations.&lt;/p&gt;

&lt;p&gt;Let's get started!&lt;/p&gt;

&lt;p&gt;Create a new view controller and name it &lt;code&gt;NoteDetailViewController&lt;/code&gt;; Again, make sure not to check “Also create XIB file” option. &lt;/p&gt;

&lt;p&gt;This will display the note and also allow us edit it.&lt;/p&gt;

&lt;p&gt;Now let’s give our view controller’s main view a colour of .systemBackground as follows.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;view.backgroundColor = .systemBackground&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now let’s add the UI Views for our note. The &lt;code&gt;NoteDetailViewController&lt;/code&gt; will look a lot like the &lt;code&gt;AddNoteViewController&lt;/code&gt; but with some additional components.&lt;br&gt;
Let’s add the title text field as an anonymous closure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private var titleField: UITextField = {
        let field = UITextField()
        field.textColor = .label
        field.font = UIFont.systemFont(
                      ofSize: 22, weight: .medium)
        return field
     }() 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also add the body text view as an anonymous closure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private var bodyTextView: UITextView = {
        let view = UITextView()
        view.font = UIFont.systemFont(ofSize: 18)
        view.textColor = .label
        view.clipsToBounds = true
        return view
    }()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s add the views as subviews to the controller's main view and define their frames by overriding the &lt;code&gt;viewWillLayoutSubviews&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        view.addSubViews(views: titleField, bodyTextView)

        titleField.frame = CGRect(
                           x: 12, 
                           y: 120, 
                           width: view.width - 24, 
                           height: 44)
        bodyTextView.frame = CGRect(
                           x: 8, 
                           y: titleField.bottom + 8, 
                           width: view.width - 16, 
                           height: view.bottom - 220)
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note let’s create a public &lt;code&gt;note&lt;/code&gt; property in our &lt;code&gt;NoteDetailViewController&lt;/code&gt; as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;var note: Note?&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Remember the &lt;code&gt;NoteDetailViewController&lt;/code&gt; displays the detail of a selected note in the &lt;code&gt;NotesViewController&lt;/code&gt;, that means it expects that a &lt;code&gt;note&lt;/code&gt; object will be passed to it when you tap on a note from the list of notes in the &lt;code&gt;NotesViewController&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, in our &lt;code&gt;viewDidLoad&lt;/code&gt;, let's set value to our &lt;code&gt;titleTextField&lt;/code&gt; and &lt;code&gt;bodyTextView&lt;/code&gt; as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if let note = note {
        titleField.text = note.title
        bodyTextView.text = note.body
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because the &lt;code&gt;note&lt;/code&gt; property is nullable, we check if it's not null to use it.&lt;/p&gt;

&lt;p&gt;Great job!&lt;/p&gt;

&lt;p&gt;Now let's go back to our &lt;code&gt;NotesViewController&lt;/code&gt; class to handle selecting a note to view it's detail.&lt;/p&gt;

&lt;p&gt;Now we’ll implement the collectionView delegate method &lt;code&gt;didSelectItemAt&lt;/code&gt; indexPath as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    func collectionView(_ collectionView: UICollectionView, 
           didSelectItemAt indexPath: IndexPath) {

        guard let note = self.dataSource.itemIdentifier(for: 
               indexPath) else {
            collectionView.deselectItem(
               at: indexPath, animated: true)
            return
        }

        let noteVC = NoteDetailViewController()
        noteVC.note = note

        navigationController?.pushViewController(
               noteVC, animated: true)
    } 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because we’ve implemented our collection view with a diffable datasource, to get the element at &lt;code&gt;indexPath&lt;/code&gt;, we call the &lt;code&gt;itemIdentifier&lt;/code&gt; of the &lt;code&gt;dataSource&lt;/code&gt; and pass it the indexPath.&lt;/p&gt;

&lt;p&gt;Now when we build and run, we should see something like the following:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fozdlsz2g44t1anmrvsl5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fozdlsz2g44t1anmrvsl5.png" alt="Note detail screen" width="634" height="1412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Great Job!&lt;/p&gt;

&lt;h2&gt;
  
  
  UPDATE MANAGED OBJECT
&lt;/h2&gt;

&lt;p&gt;Not that we’ve been able to create and read from Core data, let’s proceed to update.&lt;/p&gt;

&lt;p&gt;Remember that our &lt;code&gt;NoteDetailViewController&lt;/code&gt;, like the &lt;code&gt;AddNoteViewController&lt;/code&gt; also uses UITextField for Title and UITextView for the body of our notes.&lt;/p&gt;

&lt;p&gt;Thus, let’s set the &lt;code&gt;NoteDetailViewController&lt;/code&gt; as the &lt;code&gt;delegate&lt;/code&gt; for the &lt;code&gt;titleTextField&lt;/code&gt; and the &lt;code&gt;bodyTextView&lt;/code&gt;. This will allow us to be able to watch for changes.&lt;br&gt;
Add the following snippet to &lt;code&gt;viewDidLoad&lt;/code&gt; in the &lt;code&gt;NoteDetailViewController&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    bodyTextView.delegate = self
    titleField.delegate = self
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will immediately tell us to conform to the &lt;code&gt;UITextViewDelegate&lt;/code&gt; and the &lt;code&gt;UITextFieldDelegate&lt;/code&gt; protocols&lt;/p&gt;

&lt;p&gt;Add the following at the bottom outside of the class definition:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension NoteDetailViewController: UITextViewDelegate, 
     UITextFieldDelegate {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember we created some convenience properties and method as extensions to the UIView, let do the same for String.&lt;br&gt;
Add the following snippet to your &lt;strong&gt;Extensions.swift&lt;/strong&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension String {
   func trim() -&amp;gt; String {
      self.trimmingCharacters(in: .whitespacesAndNewlines)
   }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a shorthand version of the standard &lt;code&gt;trimmingCharaters(:)&lt;/code&gt; &lt;strong&gt;String&lt;/strong&gt; method.&lt;/p&gt;

&lt;p&gt;Thanks to Swift, we can leave out the &lt;code&gt;return&lt;/code&gt; keyword for a single line statement.&lt;/p&gt;

&lt;p&gt;In a note app, we want the app to trigger and update when the title field detects that the title has changed and the body text view to update the body content when the that changes as well.&lt;/p&gt;

&lt;p&gt;To help us achieve this, we’re going to be implementing the &lt;code&gt;textFieldDidEndEditing&lt;/code&gt; delegate method of the &lt;code&gt;UITextFieldDelegate&lt;/code&gt; protocol and the &lt;code&gt;textViewDidEndEditing&lt;/code&gt; method of the &lt;code&gt;UITextViewDelegate&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Add the following inside the &lt;code&gt;NoteDetailViewController&lt;/code&gt; extension we just added at the bottom:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension NoteDetailViewController: UITextViewDelegate, 
    UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {

    }

    func textViewDidEndEditing(_ textView: UITextView) {

    }       
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note let’s add a property name appDelegate to the &lt;code&gt;NoteDetailViewController&lt;/code&gt; just below the note declaration as follows: &lt;/p&gt;

&lt;p&gt;&lt;code&gt;let appDelegate = UIApplication.shared.delegate as! AppDelegate&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now, inside our &lt;code&gt;textFieldDidEndEditing&lt;/code&gt; delegate method, we want core data to update the title when the title text field detect a change and the user has ended editing. &lt;br&gt;
Add the following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        resignFirstResponder()
        guard let note = self.note else { return }
        if textField == titleField &amp;amp;&amp;amp; 
               titleField.text!.trim() != note.title {

            let managedContext = 
                 appDelegate.persistentContainer.viewContext
            note.title = titleField.text!.trim()

            do {
                try managedContext.save()
            } catch let error as NSError {
                fatalError("\(error.userInfo)")
            }
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also inside the textViewDidEndEditing delegate method, to update the body, add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        resignFirstResponder()
        guard let note = self.note else { return }
        if textView == bodyTextView &amp;amp;&amp;amp; 
                 bodyTextView.text.trim() != note.body {

            let managedContext = 
                 appDelegate.persistentContainer.viewContext
            note.body = bodyTextView.text

            do {
                try managedContext.save()
            } catch let error as NSError {
                fatalError("\(error.userInfo)")
            }
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice that we have to first check if the changes is not the same with the content of the note title or the body before persisting changes.&lt;/p&gt;

&lt;p&gt;Note let’s build and run. &lt;/p&gt;

&lt;p&gt;We’ve now implemented Update.&lt;/p&gt;

&lt;h2&gt;
  
  
  DELETING MANAGED OBJECT
&lt;/h2&gt;

&lt;p&gt;Now let’s implement the Delete operation. To do so, let’s go back to our &lt;code&gt;NotesViewController&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Remember that we used &lt;code&gt;UICollectionLayoutListConfiguration&lt;/code&gt; (i.e List Layout) which gives us a similar view as a &lt;strong&gt;UITableView&lt;/strong&gt;.&lt;br&gt;
In order to be able to swipe to delete as in the case of UITableView, we need to add Swipe action to our List layout configuration. Now go inside the private method named &lt;code&gt;createLayout&lt;/code&gt; and add the following snippet just before the &lt;strong&gt;return statement&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;config.trailingSwipeActionsConfigurationProvider = { 
        indexPath in

    let deleteAction = UIContextualAction(
           style: .destructive, title: "Delete") {              
         [weak self] action, view, completion in

       self?.deleteItem(at: indexPath)
       completion(true)

    }
    return UISwipeActionsConfiguration(
                          actions: [deleteAction])
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You could also create one for the &lt;code&gt;leadingSwipeActionsConfigurationProvider&lt;/code&gt; if there’s need for that.&lt;/p&gt;

&lt;p&gt;Now we need to create a method called &lt;code&gt;deleteItem(at:)&lt;/code&gt;. So add the following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private func deleteItem(at indexPath: IndexPath) {
   guard let appDelegate = UIApplication.shared.delegate 
                  as? AppDelegate else { return }

   let managedContext = 
             appDelegate.persistentContainer.viewContext

   let note = self.dataSource.itemIdentifier(for: indexPath)        
   guard let note = note else { return }

   managedContext.delete(note)

   do {
       try managedContext.save()
       var snapshot = dataSource.snapshot()

       snapshot.deleteAllItems()
       snapshot.appendSections([.main])
       dataSource.apply(snapshot)

       fetchNotes()
       updateCollectionView()

   } catch let error as NSError {
       fatalError("\(error.userInfo)")
   }    
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the method above, first we get a &lt;code&gt;managedContext&lt;/code&gt; from the persistent container in the AppDelegate. Then we find the &lt;code&gt;note&lt;/code&gt; at the swiped &lt;code&gt;indexPath&lt;/code&gt;.&lt;br&gt;
Then we passed the &lt;code&gt;note&lt;/code&gt; to the delete method of the managed context. Finally and importantly, we called the &lt;code&gt;save()&lt;/code&gt; method on the &lt;code&gt;managedContext&lt;/code&gt; to commit the actual deletion.&lt;/p&gt;

&lt;p&gt;Now to update our UI (i.e remove the deleted from snapshot), we had to clear the snapshot, reassigned the main section before fetching and updating the CollectionView.&lt;/p&gt;

&lt;p&gt;Now let’s build and run again. If everything is fine, we should be able to swipe a cell and see it deleted when the delete action button is tapped. &lt;/p&gt;

&lt;p&gt;We've come to end of the project. The complete source code can be found &lt;a href="https://github.com/TayoDavid/Notes" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Create a Note App with Swift and Core Data</title>
      <dc:creator>OLAWOYE OMOTAYO</dc:creator>
      <pubDate>Wed, 11 May 2022 21:27:30 +0000</pubDate>
      <link>https://forem.com/omotayodavid/create-a-note-app-with-swift-and-core-data-h2p</link>
      <guid>https://forem.com/omotayodavid/create-a-note-app-with-swift-and-core-data-h2p</guid>
      <description>&lt;p&gt;In this tutorial, I’m going to walk you through how to create a note iOS app.&lt;/p&gt;

&lt;p&gt;What you’ll learn:&lt;/p&gt;

&lt;p&gt;Create UIKit layout programmatically&lt;br&gt;
Data Persistence with Core data - Create, Read, Update and Delete notes.&lt;br&gt;
Dismiss presented view controller when UIAlertAction is tapped.&lt;/p&gt;

&lt;p&gt;Let’s Get Started!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsdxmmb3txmam35i9816r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsdxmmb3txmam35i9816r.png" alt="Create A New Project" width="800" height="481"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In your Main.storyboard file, Embed the View Controller inside a Navigation View Controller.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa4k50zyp9qpifp85dfj3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fa4k50zyp9qpifp85dfj3.png" alt="Embed View Controller inside a Navigation Controller" width="800" height="456"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on the Navigation bar of the Navigation View Controller and toggle the Inspection Pane Open and under the style option, check prefer large titles. &lt;br&gt;
Importantly, In the inspector pane, make sure the Navigation Controller has “Is Initial View Controller” option checked.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F38jisnb00d89ol75gc7t.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F38jisnb00d89ol75gc7t.png" alt="Set Large title" width="800" height="481"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, let’s rename our default view controller created for us to &lt;code&gt;NotesViewController&lt;/code&gt; To do that, Option click the ViewController class name as follows: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnegysixz96rjsj7sqta5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnegysixz96rjsj7sqta5.png" alt="Rename View Controller" width="800" height="531"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Inside our &lt;code&gt;viewDidLoad&lt;/code&gt; method, let give the &lt;code&gt;NotesViewController&lt;/code&gt; a title and a RightBarButtonItem to add new notes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;       title = "Notes"
       navigationItem.rightBarButtonItem = UIBarButtonItem(
            barButtonSystemItem: .add, 
            target: self, 
            action: #selector(didTapAddButton)
       )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note let’s create a private &lt;code&gt;@objc&lt;/code&gt; function to handle our bar button item.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @objc
    private func didTapAddButton() {

    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's run our app to see our progress. It should look something like this: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foxgbriuwpmnubzy32keb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foxgbriuwpmnubzy32keb.png" alt="First App Run" width="800" height="650"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You should see either of the screens above depending on whether your device is on light or dark mode. Cool &lt;/p&gt;

&lt;p&gt;Now let’s go ahead to create the Add Note ViewController. To do that, create a new Cocoa Touch Class. Make sure not to check the “Also create XIB file” option, unless you’re confident about your Interface Builder skills.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnhjsd7uap9o1mqktsx5h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnhjsd7uap9o1mqktsx5h.png" alt="Create AddNoteViewController" width="800" height="481"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now set the background colour for the &lt;code&gt;AddNoteViewController&lt;/code&gt; to .systemBackground in side the &lt;code&gt;viewDidLoad&lt;/code&gt; method as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;view.backgroundColor = .systemBackground&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Without that, the view controller would be transparent and you wouldn't know it's presented.&lt;/p&gt;

&lt;p&gt;Great! Now let's go back to the NotesViewController and add the following code snippet to the private method we created, &lt;code&gt;didTapAddButton&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let addNoteVC = AddNoteViewController()
let navVC = UINavigationController(rootViewController: addNoteVC)
navVC.navigationBar.prefersLargeTitles = true
navVC.modalPresentationStyle = .formSheet
present(navVC, animated: true, completion: nil)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don't worry too much about the NavigationController. I added it because I wanted the view controller to have a Navigation bar.&lt;/p&gt;

&lt;p&gt;Next thing is to create views on the add note view controller, but before that, let's create some convenience properties and method as an extension to UIView &lt;/p&gt;

&lt;p&gt;Create a new swift file named Extensions and add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    import UIKit

    extension UIView {
        /// Weight of view
        var width: CGFloat {
            frame.size.width
        }

        /// Height of view
        var height: CGFloat {
            frame.size.height
        }

        /// Left edge of view
        var left: CGFloat {
            frame.origin.x
        }

        /// Right edge of view
        var right: CGFloat {
            left + width
        }

        /// Top edge of view
        var top: CGFloat {
            frame.origin.y
        }

        /// Bottom edge of view
        var bottom: CGFloat {
            top + height
        }

        func addSubViews(views: UIView...) {
            for view in views {
                self.addSubview(view)
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s create our views inside Add Note ViewController:&lt;/p&gt;

&lt;p&gt;First add the title textField as an anonymous closure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private var titleField: UITextField = {
    let field = UITextField()
    field.placeholder = "Title"
    field.textColor = .label
    field.font = UIFont.systemFont(ofSize: 20, weight:.medium)
    return field
}()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then add the body text view.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private var bodyTextView: UITextView = {
        let view = UITextView()
        view.text = "Type in here..."
        view.font = UIFont.systemFont(ofSize: 18)
        view.textColor = .placeholderText
        view.clipsToBounds = true
        return view
    }()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now override the &lt;code&gt;viewWillLayoutSubviews&lt;/code&gt; by defining frame for our views in the view controller’s view.&lt;/p&gt;

&lt;p&gt;First add the views as subviews to the controller's main view as follows:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;view.addSubViews(views: titleField, bodyTextView)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Remember we created a convenience method as an extension of UIView called &lt;code&gt;addSubviews()&lt;/code&gt; which can take a varying number of views instead of calling addSubview multiple times.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;titleField.frame = CGRect(
     x: 20, 
     y: 120, 
     width: view.width - 40, 
     height: 44
)
bodyTextView.frame = CGRect(
     x: 16, 
     y: titleField.bottom + 20, 
     width: view.width - 32, 
     height: view.bottom - 250
)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now add the following inside &lt;code&gt;viewDidLoad&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    title = "Add Note"
    navigationItem.rightBarButtonItem = UIBarButtonItem(
            title: "Save", 
            style: .done, 
            target: self, 
            action: #selector(didTapSaveButton)
    )
    bodyTextView.delegate = self
    titleField.delegate = self
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have now added a &lt;code&gt;rightBarButtonItem&lt;/code&gt; to the navigation bar which we’ll tap to save the note.&lt;/p&gt;

&lt;p&gt;Now create the &lt;code&gt;didTapSaveButton&lt;/code&gt; method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@objc
private func didTapSaveButton() {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your editor pane would be showing some errors right now, because we need to conform to the &lt;code&gt;UITextFieldDelegate&lt;/code&gt; and the &lt;code&gt;UITextViewDelegate&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;Now create an extension of the &lt;code&gt;AddNoteViewController&lt;/code&gt; at the bottom of the screen outside the &lt;code&gt;AddNoteViewController&lt;/code&gt; class as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension AddNoteViewController: UITextFieldDelegate, UITextViewDelegate {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now when you build and run, we should have something that looks as follows:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ltxhy3e1poiw22pvte1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4ltxhy3e1poiw22pvte1.png" alt="Add Note VC" width="634" height="1412"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now inside the extension, let implement the delegate functions as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    func textFieldDidEndEditing(_ textField: UITextField) {
        titleField.resignFirstResponder()
        if textField == titleField &amp;amp;&amp;amp; 
            !titleField.text!.isEmpty {
            bodyTextView.becomeFirstResponder()
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -&amp;gt; 
        Bool {
        titleField.resignFirstResponder()
        bodyTextView.becomeFirstResponder()
        return true
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView == bodyTextView &amp;amp;&amp;amp; 
           bodyTextView.text == "Type in here..." {
            textView.text = ""
            bodyTextView.textColor = .label
        }
    }

    func textViewDidEndEditing(_ textView: UITextView) {
        if textView == bodyTextView &amp;amp;&amp;amp; 
           bodyTextView.text.isEmpty {
            textView.text = "Type in here..."
            bodyTextView.textColor = .placeholderText
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So far we've been working on the UI, now to the part we've been waiting for.&lt;/p&gt;

&lt;h2&gt;
  
  
  PERSISTING DATA TO CORE DATA.
&lt;/h2&gt;

&lt;p&gt;Core data is Apples framework for managing object graph and persisting data to disk. Although core data can persist data to disk, it is mainly for managing object graph in your application.&lt;/p&gt;

&lt;p&gt;To use core data in our app, we need to first create a “Data Model file”. This is to define the structure of the necessary objects. &lt;br&gt;
Remember when creating our project, we had the “Use core data” Option checked which creates this Data model file for us by default.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzeukyejsfz5a3cgqbn1o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzeukyejsfz5a3cgqbn1o.png" alt="Data Model File" width="800" height="480"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now click on the Add Entity button and rename that to Note. Afterwards add attributes (with names and types) by clicking the plus button.&lt;br&gt;
Lastly, toggle open your inspector pane AND CHANGE THE “Codegen” Option to “Manual/None” because we’ll like to create our model class ourselves. &lt;br&gt;
You’ll see the reason for this in a sec.&lt;/p&gt;

&lt;p&gt;Now let’s create a swift file named “model”. You could name it anything, I’m just naming it that since there’re not too many model in this sample app.&lt;br&gt;
Inside the model file, let’s create an Enum and a class for our entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    import CoreData

    enum Section: Hashable {
        case main
    }

    @objc(Note)
    public class Note: NSManagedObject {

        @NSManaged public var title: String
        @NSManaged public var body: String
        @NSManaged public var created: Date

    }

    extension Note {
        @nonobjc public class func fetchRequest() -&amp;gt; 
             NSFetchRequest&amp;lt;Note&amp;gt; {
            NSFetchRequest&amp;lt;Note&amp;gt;(entityName: "Note")
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;NSManagedObject is like an instance of your Entity (which can be liken to a class).&lt;/p&gt;

&lt;p&gt;We’ll be using a Diffable DataSource and UICollectionView later on in our &lt;code&gt;NotesViewController&lt;/code&gt;. The enum represents our section for the CollectionView.&lt;/p&gt;

&lt;p&gt;Now that we’ve created an entity, let’s go back to our &lt;code&gt;AddNoteViewController&lt;/code&gt; to complete adding notes to our app. Inside your &lt;code&gt;didTapSaveButton&lt;/code&gt; method, let add the following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if titleField.text!.isEmpty || bodyTextView.text.isEmpty {
   let alertController = UIAlertController(
       title: "Fields Required",
       message: "Please enter a title and body for your 
                 note!",
       preferredStyle: .alert
   )

   let cancelAction = UIAlertAction(
       title: "Ok", 
       style: .cancel, 
       handler: nil
   )
   alertController.addAction(cancelAction)

   present(alertController, animated: true)
   return
}

guard let appDelegate = UIApplication.shared.delegate 
     as? AppDelegate else { return }

let managedContext = appDelegate
                        .persistentContainer
                        .viewContext

let note = Note(context: managedContext)

note.title = titleField.text!
note.body = bodyTextView.text
note.created = Date.now

do {
    try managedContext.save()

    let alertController = UIAlertController(
         title: "Note Saved", 
         message: "Note has been saved successfully!", 
         preferredStyle: .alert
    )

    let okayAction = UIAlertAction(
          title: "Ok", 
          style: .cancel) { [weak self] _ in
       guard let self = self else { return }
       self.dismiss(animated: true) {
           self.dismiss(animated: true, completion: nil)
       }
    }

    alertController.addAction(okayAction)
    present(alertController, animated: true)

} catch let error as NSError {
    fatalError("Error saving person to core data. 
             \(error.userInfo)")
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wooops… Great one! &lt;/p&gt;

&lt;p&gt;Now when we run our app and tap on the add button to add a note we’ll be able to add a new note and dismiss on success.&lt;/p&gt;

&lt;p&gt;One last thing before we go back to our Home Screen (&lt;code&gt;NotesViewController&lt;/code&gt;) which shows a list of all the notes we’ve added.&lt;/p&gt;

&lt;p&gt;Create a custom delegate to notify the &lt;code&gt;NotesViewController&lt;/code&gt; that we’ve successfully added a new note.&lt;/p&gt;

&lt;p&gt;At the very top of the &lt;code&gt;AddNoteViewController&lt;/code&gt;, just before the class definition, Add the following snippet:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    protocol AddNoteViewControllerDelegate {
        func didFinishAddingNote()
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, inside the &lt;code&gt;AddNoteViewController&lt;/code&gt;, let’s create delegate property and call the delegate function inside the &lt;code&gt;okayAction&lt;/code&gt; of the &lt;code&gt;didTapSaveButton&lt;/code&gt; method as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AddNoteViewController: UIViewController {

    var delegate: AddNoteViewControllerDelegate?

    ...

    @objc
    private func didTapSaveButton() {       
      ...
      let okayAction = UIAlertAction(
        title: "Ok",
        style: .cancel) { [weak self] _ in
            guard let self = self else { return }

            self.delegate?.didFinishAddingNote() 

            self.dismiss(animated: true) {
                self.dismiss(animated: true, completion: nil)
            }
        }
        ...
    }    
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  WORKING WITH UICOLLECTIONVIEW LIST LAYOUT
&lt;/h2&gt;

&lt;p&gt;Inside our NotesViewController, let add the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private var dataSource: 
    UICollectionViewDiffableDataSource&amp;lt;Section, Note&amp;gt;! = nil
private var notesCollectionView: UICollectionView! = nil    
private var notes: [Note]?

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remember we create the Section and Note model, in our model.swift file.&lt;br&gt;
Now, let configure the Collection View we’ve created by adding the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private func createLayout() -&amp;gt; UICollectionViewLayout {
    let config = UICollectionLayoutListConfiguration(
                    appearance: .plain)
    return UICollectionViewCompositionalLayout.list(
                    using: config)
}

private func configureCollectionView() {
    notesCollectionView = UICollectionView(
              frame: view.bounds, 
              collectionViewLayout: createLayout()
    )
    notesCollectionView.autoresizingMask = 
              [.flexibleWidth, .flexibleHeight]
    view.addSubview(notesCollectionView)
    notesCollectionView.delegate = self
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you need to conform to the UICollectionViewDelegate protocol, add the following outside the class definition of the NotesViewController:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension NotesViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, 
        didSelectItemAt indexPath: IndexPath) {      
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have to conform to the &lt;code&gt;didSelectItemAt&lt;/code&gt; indexPath method to go to the note detail screen.&lt;/p&gt;

&lt;p&gt;Now, we’ve successfully configured our collection view, let’s also configure the dataSource. To do that, add the following method to NotesViewController:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private func configureDataSource() {
    let cellRegistration = UICollectionView
        .CellRegistration&amp;lt;UICollectionViewListCell, Note&amp;gt; { 
          cell, indexPath, note in
    var content = cell.defaultContentConfiguration()
    content.text = note.title
    content.textToSecondaryTextVerticalPadding = 8
    content.textProperties.font = UIFont.systemFont(
         ofSize: 18, 
         weight: .medium
    )
    content.textProperties.color = .label
    content.secondaryTextProperties.font = 
                  UIFont.systemFont(ofSize: 16)
    content.secondaryTextProperties.color = .secondaryLabel

    let bodyTextArray = note.body.components(separatedBy: " ")

    if (bodyTextArray.count &amp;gt; 8) {
       var bodyText = bodyTextArray[0...8]
                         .joined(separator: " ")
       bodyText.append("...")
       content.secondaryText = bodyText
    } else {
       content.secondaryText = note.body            
    }

    cell.contentConfiguration = content
    cell.accessories = [.disclosureIndicator()]
  }

dataSource = UICollectionViewDiffableDataSource&amp;lt;Section, Note&amp;gt; 
       (collectionView: notesCollectionView) {
       (collectionView: UICollectionView, 
        indexPath: IndexPath, 
        note: Note) -&amp;gt; UICollectionViewCell? in
    return collectionView.dequeueConfiguredReusableCell(
        using: cellRegistration, 
        for: indexPath, 
        item: note
    )
}

    var snapshot = 
      NSDiffableDataSourceSnapshot&amp;lt;Section, Note&amp;gt;()
     snapshot.appendSections([.main])

    if let notes = notes {
        snapshot.appendItems(notes)
    }
    dataSource.apply(snapshot, animatingDifferences: true)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, we registered the cell for the UICollection View and then configure the data source.&lt;/p&gt;

&lt;p&gt;Build and run your app to be sure there’s no error.&lt;/p&gt;

&lt;p&gt;Now let add the following two methods to our controller. First to fetch the data from Core Data and the other to update our UI&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private func fetchNotes() {
    guard let appDelegate = UIApplication.shared.delegate 
        as? AppDelegate else { return }
    let managedContext = 
        appDelegate.persistentContainer.viewContext

    do {
        notes = try managedContext.fetch(Note.fetchRequest())
    } catch let error as NSError {
       fatalError("Unable to fetch. \(error) = 
              \(error.userInfo)")
    }
}

private func updateCollectionView() {
    guard let notes = notes else {
        return
    }
    var snapshot = dataSource.snapshot()
    snapshot.appendItems(notes)
    dataSource.apply(snapshot, animatingDifferences: true)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great work!&lt;/p&gt;

&lt;p&gt;Now let’s call the &lt;code&gt;configureCollectionView&lt;/code&gt; and &lt;code&gt;configureDataSource&lt;/code&gt; methods from inside &lt;code&gt;viewDidLoad&lt;/code&gt; as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; override func viewDidLoad() {
     super.viewDidLoad()

     ...

     configureCollectionView()
     configureDataSource()
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now override the &lt;code&gt;viewWillAppear&lt;/code&gt; method and call the &lt;code&gt;fetchNotes&lt;/code&gt; method from inside it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;override func viewWillAppear(_ animated: Bool) {
    fetchNotes()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also override the &lt;code&gt;viewDidAppear&lt;/code&gt; method and call the &lt;code&gt;updateCollectionView&lt;/code&gt; method from inside it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;override func viewDidAppear(_ animated: Bool) {
    updateCollectionView()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great!!!&lt;/p&gt;

&lt;p&gt;Now we can run our app. If everything is okay, we should see the following.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhw8w0h65hhzprnk5w4mc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhw8w0h65hhzprnk5w4mc.png" alt="NotesViewController showing data" width="636" height="1396"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, before we wrap it up for this part 1, remember we created a delegate in our &lt;code&gt;AddNoteViewController&lt;/code&gt; which should notify the &lt;code&gt;NotesViewController&lt;/code&gt; after adding a new note to the database. &lt;/p&gt;

&lt;p&gt;Remember, we navigate to AddNoteVC by calling the &lt;code&gt;didTapAddButton&lt;/code&gt; method. Now set the delegate for the “addNoteVC” instance as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    @objc
    private func didTapAddButton() {
        let addNoteVC = AddNoteViewController()
        addNoteVC.delegate = self        
        ...
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will require us to conform to the &lt;code&gt;AddNoteViewControllerDelegate&lt;/code&gt; and implement the   &lt;code&gt;didFinishAddingNote&lt;/code&gt; method as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;extension NotesViewController: AddNoteViewControllerDelegate {
    func didFinishAddingNote() {
        fetchNotes()
        updateCollectionView()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We again, call the &lt;code&gt;fetchNotes&lt;/code&gt; and &lt;code&gt;updateCollectionView&lt;/code&gt; methods from inside there.&lt;/p&gt;

&lt;p&gt;Great! Now when we create a new note, it immediately update the NotesViewController.&lt;/p&gt;

&lt;p&gt;Here's a link to &lt;a href="https://github.com/TayoDavid/Notes" rel="noopener noreferrer"&gt;source code&lt;/a&gt; on GitHub.&lt;/p&gt;

&lt;p&gt;In the &lt;a href="https://dev.to/omotayodavid/create-a-note-app-with-swift-and-core-data-ii-28el"&gt;Second Part of this article&lt;/a&gt;, we’ll cover how to update and delete notes.&lt;/p&gt;

</description>
      <category>ios</category>
      <category>swift</category>
      <category>coredata</category>
      <category>uicollectionviewlistlayout</category>
    </item>
  </channel>
</rss>
