Saturday, November 21, 2026
HomeiOS DevelopmentManaging SQLite Database with SwiftyDB

Managing SQLite Database with SwiftyDB

[ad_1]

Selecting a approach for storing information completely is one thing that’s at all times wanted when creating purposes. There are numerous choices we will choose from: To create single recordsdata, to make use of CoreData or create a SQLite database. The final possibility contains some additional problem because the database should be created first, and all tables and fields to be already outlined earlier than an app makes use of them. Moreover, and from the programming standpoint, it’s not that simple to handle a SQLite database when information must be saved, up to date or retrieved.

These issues appear to vanish when utilizing a comparatively new library that was popped on the GitHub known as SwiftyDB. It’s a third-party library, which, because the creator says, is a plug-and-play element certainly. SwiftyDB reliefs builders from the trouble of making a SQLite database manually, and from defining all required tables and fields. That occurs robotically by the library utilizing the properties of the category (or lessons) used as information fashions. Apart from that, all database operations are carried out below the hood, so builders can give attention to the implementation of the app logic solely. A easy but highly effective API makes it actually a chunk of cake when coping with the database.

It’s crucial to say although that you simply shouldn’t anticipate SwiftyDB to make miracles. It’s a dependable library that may do fairly nicely what it’s speculated to do, however there are nonetheless some lacking options which might be most likely meant to be added within the (close to or distant) future. Nevertheless, it’s nonetheless remaing an important device that deserves some particular consideration, subsequently on this tutorial we’ll undergo the fundamentals of SwiftyDB.

To your reference, you’ll find its documentation right here, which you must undoubtedly see after having gone by way of this textual content. Should you have been at all times keen to work with SQLite databases however hesitated to take action, I imagine that SwiftyDB is an effective begin to try this.

With the above stated, let’s get going with the exploration of a brand new, fairly promising device.

Concerning the Demo App

In our publish immediately we’re going to create a extremely easy notice taking app able to doing all the essential operations one would anticipate:

  • Listing notes
  • Create new notes
  • Replace present notes
  • Delete notes

Apparently, SwiftyDB goes to take cost of managing the information into an SQLite database. All of the listed operations above are ok to display all the things you want so can get began working with SwiftyDB simply.

To make it attainable for us to remain into the purpose, I’ve created a starter mission which you must obtain and start with. While you get it, open it in Xcode and navigate round so that you get acquainted with it. As you’ll see, all the essential performance is there, with the many of the data-related options to be lacking. It might be nice in case you would additionally run the mission no less than as soon as, so that you see what’s all about.

The app is navigation based mostly, and within the first view controller there’s a tableview the place all notes are supposed to be listed.

t50_1_note_list

By tapping on an present notice we’ll be capable of edit it and replace it, and when swiping to the left we’ll be capable of delete it:

t50_2_delete_note

Composing a brand new notice is feasible by tapping on the plus (+) button on the navigation bar. With a view to have a ok working instance, right here’s an inventory of actions that we will carry out when enhancing a notice (new or present one):

  1. Set title and physique for the notice.
  2. Change the font identify.
  3. Change the font dimension.
  4. Change the textual content shade.
  5. Import photos to the notice.
  6. Transfer the photographs round and place them to a distinct place.

All values matching to the above operations might be saved to the database. To make it a bit extra clear for the final two components particularly, the precise photos are going to be saved to the paperwork listing of the app, whereas we’re going to save simply the identify and body for every picture to the database. However not simply that; moreover we’re going to create a brand new class for managing photos (with the small print are coming later).

t50_3_edit_note

A final however necessary element I’ve to say about is that regardless that you’re downloading a starter mission to work on, by the tip of the following half you’ll be having a workspace. That’s as a result of we’ll use CocoaPods to obtain the SwiftyDB library, and another dependencies that come alongside.

Please get going whenever you’re as much as it, however first, shut the starter mission if in case you have already opened it in Xcode.

Putting in SwiftyDB

The very first thing we’ve to do is to obtain the SwiftyDB library and use it in our mission. Merely getting the library recordsdata and including them to the mission isn’t going to work, so we’ve to carry out the set up utilizing the CocoaPods dependency supervisor. The method is easy, and also you’ll be capable of do it very quickly in any respect, even if in case you have by no means used CocoaPods earlier than. For you reference nevertheless, have a look to the earlier hyperlink.

Putting in CocoaPods

We’re going to start by putting in CocoaPods to our system. If in case you have put in CocoaPods already please skip this step. If not then go forward and open Terminal. Sort the next command to put in CocoaPods:

Press Return, present your password and sit again whereas the obtain course of is going down. Don’t shut Terminal as soon as it’s completed, we’re nonetheless needing it.

Putting in SwiftyDB and Different Dependencies

Navigate to the folder the place the starter mission exists by utilizing the cd command (nonetheless in Terminal):

It’s now time to create a Podfile that describes the library (or libraries) we need to obtain to CocoaPods. The best approach to try this is by typing the next command and let CocoaPods create one for us:

A brand new file named Podfile might be created to the mission folder. Open it utilizing a textual content editor (ideally not TextEdit), and modify it in line with the following snippet:

t50_4_podfile

The road that can really do the entire job is the pod "SwiftyDB". CocoaPods will obtain SwiftyDB library and all of its dependencies by utilizing that line, and it’ll create some new subfolders together with an Xcode workspace.

When you end enhancing the file, save and shut it. Then, just remember to’ve closed the starter mission on Xcode and return to Terminal. Sort the following command:

t50_5_pod_install_2

Wait once more for a couple of moments, and then you definately’re able to go. As a substitute of opening the starter mission, open the NotesDB.xcworkspace on Xcode this time.

t50_6_folder_after_installation

Starting With SwiftyDB – Our Mannequin

Contained in the NotesDB mission there’s a file known as Notice.swift, nevertheless it’s presently empty. That is our entry level immediately, as we’re going to create a few lessons that can symbolize a notice entity programmatically. In a extra theoretical stage, our upcoming work right here consists of the Mannequin half within the iOS MVC sample.

What we’d like initially is to import the SwiftyDB library, in order you guess go to the highest of the file and add this line:

Now, let’s declare our most necessary class on this mission:

When working with SwiftyDB there are a couple of however particular guidelines to comply with, and within the above class header line you’ll be able to see two of them:

  1. A category with properties meant to be saved in a database utilizing SwiftyDB should be a subclass of the NSObject class.
  2. A category with properties meant to be saved in a database utilizing SwiftyDB should undertake the Storable protocol (it’s a SwiftyDB protocol).

Now we’ve to consider the properties we need to have on this class, and right here it comes once more a brand new rule from SwiftyDB: The datatypes of the properties should be any of these listed right here so as to have the ability to load total Notice objects, as a substitute of easy information (array with dictionaries) when retrieving information from the database. If there are properties with “incompatible” datatypes, then we’ll should take additional actions so we convert them into the prompt ones (we’ll see that in particulars in only a whereas). By default, properties with such datatypes are merely ignored by SwiftyDB when it’s about time to save lots of to database, and no respective fields are created to the desk. Additionally, we’ll give particular therapy to another properties within the class that we don’t actually need to be saved to the database.

The final rule for now says {that a} class that conforms to the Storable protocol should essentially implement the init technique:

Now that we’ve all the information we’d like, let’s begin declaring the properties of our class. Not all for now, as a few of them require extra dialogue. Nevertheless, listed here are the fundamentals:

Unnecessary to remark any of them, apart from the primary one. When that object will get initialised it is going to create a brand new database (named notes.sqlite) if it doesn’t exist and it’ll create a desk robotically. The desk fields will match to the properties having a correct datatype. Then again, if the database already exists, it is going to simply open.

As you would possibly discover, the above properties describe a notice and all of the attributes we need to save (title, textual content, textual content shade, font identify and dimension, creation and modification dates), however there’s nothing there relating to the photographs {that a} notice can probably have. Deliberately, we’re going to create a brand new class for photos, the place we’ll retailer two properties solely: The body and the picture identify.

So, nonetheless being within the Notice.swift file, create the next class above or beneath the prevailing one:

Notice that the body is represented as a NSData object on this class, and never as a CGRect. It’s essential to do it that approach, so we will simply retailer that worth to the database later. You’ll see shortly how we’re going to deal with it, and also you’ll additionally perceive why we undertake the NSCoding protocol.

Again to the Notice class, let’s declare an ImageDescriptor array as proven subsequent:

There’s a limitation that now could be the perfect time to say about, and that’s the undeniable fact that SwiftyDB would not retailer collections to the database. In easy phrases, that implies that our photos array won’t ever be saved to the database, so we’ve to determine tips on how to cope with this. What we’re allowed to do is to make use of one of many supported datatypes (see the hyperlink I supplied a bit after the start of this half), and essentially the most appropriate datatype is NSData. So, as a substitute of saving the photos array to the database, we’ll be saving the next (new) property:

However how are we speculated to go from the photos array with ImageDescriptor objects to the imagesData NSData object? Properly, the reply is by archiving the photos array utilizing the NSKeyedArchiver class and producing that approach a NSData object. We’ll see later how that is actually being achieved in code, however now that we all know what we’ve to do, we should return to the ImageDescriptor class and have some additions.

As , a category might be archived (in different languages also referred to as serialized) if solely all of its properties might be serialised too, and in our case that is attainable, because the datatypes (NSData and String) of the 2 properties within the ImageDescriptor class are serialisable. Nevertheless that’s not sufficient, as we additionally should encode and decode them in an effort to efficiently archive and unarchive respectively, and that’s why we really want the NSCoding protocol. By utilizing it we’ll implement the strategies proven subsequent (one among them is an init technique), and we’ll correctly encode and decode our two properties:

For extra details about the NSCoding protocol and the NSKeyedArchiver class have a look right here and right here, it’s pointless to debate extra about them right here and now.

Along with all of the above, let’s outline a fairly helpful customized init technique. It’s actually easy, so no have to make any feedback:

At this level our first fast assembly with the SwiftyDB library involves its finish. Despite the fact that we didn’t do a lot SwiftyDB stuff, this half was crucial for 3 causes:

  1. To create a category that might be used from the SwiftyDB.
  2. To find out about some guidelines utilized when utilizing SwiftyDB.
  3. To see some necessary limitations relating to the datatypes that may be saved within the database utilizing SwiftyDB.

Notice: Should you’re seeing some errors proper now on Xcode, then construct the mission as soon as (Command-B) to eliminate them.

Major Keys and Ignored Properties

It’s at all times really useful to make use of main keys when coping with databases, as such keys may also help you uniquely determine data within the database tables and carry out varied operations by utilizing them (for instance, replace a particular document). You could find right here a great definition about what a main secret is.

It’s simple to specify a number of properties of a category as the first key (or keys) for the respective desk within the database in SwiftyDB. The library offers the PrimaryKeys protocol, which ought to be applied by all lessons that the respective tables ought to have a main key so their objects to be uniquely recognized. The best way to try this is kind of easy and normal, so let’s get into the purpose immediately:

Within the NotesDB mission you’ll discover a file named Extensions.swift. Click on it on the Mission Navigator so that you open it. Add the next strains there:

In our demo, we would like the noteID property to be the one main key within the respective desk within the sqlite database. Nevertheless, if extra main keys are required, then you definately simply have to jot down them within the row separated by comma (for instance, return ["key1", "key2", "key3"]).

Apart from that, not all properties of a category ought to at all times be saved to the database, and you must explicitly order SwiftyDB to not embody them. For instance, within the Notice class we’ve two properties that aren’t going to be saved to the database (both as a result of they can’t or we don’t need so): The photos array and the database object. How can we explicitly exclude these two? By implementing one other protocol that the SwiftyDB library offers known as IgnoredProperties:

If there have been extra properties we wouldn’t prefer to should the database they need to be added above too. For instance, let’s say that we’ve the next property:

… and that we don’t need it to be saved to the database. In that case, we must always add it to the IgnoredProperties protocol implementation too:

Notice: Import the MARKDOWN_HASH6211c316cc840902a4df44c828a26fbeMARKDOWN_HASH library to the MARKDOWN_HASH1dbda56f2122b1744ebf59bb64bbffdfMARKDOWN_HASH file in case you see any errors.

Saving a New Notice

Having achieved the naked minimal implementation within the Notice class, it’s time to show to the functionalities of the demo app. We nonetheless haven’t added any strategies to our new class; we’ll accomplish that by following the implementation movement of all of the lacking functionalities.

So, the very first thing we’d like is having notes, subsequently the app should be instructed tips on how to save them correctly utilizing the SwiftyDB and our two new lessons. That is going to happen largely within the EditNoteViewController class, so it’s about time to open the respective file utilizing the Mission Navigator. Earlier than we write the primary line of code right here, I think about fairly necessary to spotlight the many of the properties discovered there:

  • imageViews: This array holds all of the picture view objects that comprise photos added to a notice. Please don’t neglect that this array exists; it’ll grow to be helpful shortly.
  • currentFontName: It holds the identify of the presently utilized font to the textview.
  • currentFontSize: It’s the font dimension of the textual content within the textview.
  • editedNoteID: The noteID worth (main key) of a notice that’s about to be up to date. We’ll use it later.

For the reason that normal performance already exists within the starter mission, what we’ve to do is to implement the lacking logic within the saveNote() technique. We’ll start by doing two issues: First we gained’t permit saving if there is no such thing as a textual content within the title or the physique of the notice. Second, we’ll dismiss the keyboard if it’s appeared by the point of saving:

We’ll proceed now by initializing a brand new Notice object, and by assigning the fitting values to the correct properties. The pictures want particular therapy, and we’ll do it proper after.

A couple of feedback now:

  • The noteID property expects any Int quantity that can work as the first key. You may create or generate any worth you need so long as it’s distinctive. On this case we set the integer half of the present timestamp as our main key, however typically this isn’t a good suggestion in actual world purposes because the timestamp accommodates too many digits. Nevertheless for our demo utility it’s simply superb, because it additionally consists of the best possibility for having a singular int worth.
  • As we save a notice for first time, we set the present timestamp (expressed as a NSDate object) to each creation and modification date properties.
  • The one particular motion we undoubtedly should take is to transform the textual content shade of the textview right into a NSData object. That is achieved by archiving the colour object utilizing the NSKeyedArchiver class.

Let’s give attention to tips on how to save the photographs now. We are going to create a brand new technique which might be fed with the picture views array. We’ll carry out two issues in it: We’ll save the precise picture of every picture view to the paperwork listing of the app, and we’ll create an ImageDescriptor object for each. Every such object might be appended to the photos array.

With a view to create this new technique we’re going to make a small detour, and to return to the Notice.swift file once more. Let’s see the implementation first, after which we’ll focus on about it.

<

pre lang=”swift”>
func storeNoteImagesFromImageViews(imageViews: [PanningImageView]) {
if imageViews.depend > 0 {
if photos == nil {
photos = ImageDescriptor
}
else {
photos.removeAll()
}

}

Right here’s what’s going down within the above technique:

  1. For starters we test if the photos array is initialised or not. If it’s nil we initialise it, if not, we simply take away any present information from it. The second will grow to be helpful later, after we’ll be updating an present notice.
  2. Then for every picture view we create a singular identify for its picture. Every identify might be much like this: “img_12345679_1”.
  3. We initialise a brand new ImageDescriptor object by utilizing our customized init technique and by offering the picture view body and the picture identify as parameters. The toNSData() technique has been applied as an extension of the CGRect and you’ll find it within the Extensions.swift file. Its function is to transform a body to a NSData object. As soon as the brand new ImageDescriptor object is prepared, it’s appended to the photos array.
  4. We save the precise picture to the paperwork listing. The saveImage(_: withName:) class technique might be discovered within the Helper.swift file, together with couple extra helpful class strategies.
  5. Lastly, when all picture views have been processed, we convert the photos array to a NSData object by archiving it and we assign it to the imagesData property. The final line above is the precise motive that the NSCoding protocol and the implementation of its strategies are required within the ImageDescriptor class.

The else case above might sound reduntant, nevertheless it’s required. By default, the imagesData property is nil and it’ll stay like that if no photos get added to the notice. Nevertheless, “nil” is just not acknowledged by SQLite. What SQLite understands is the equal of NSNull, and that’s what we offer transformed to a NSData object.

Again to the EditNoteViewController.swift file once more to make use of what we simply created:

Let’s return now to the Notice.swift file, and let’s implement the tactic that can carry out the precise saving to the database. There’s one thing necessary you must know at this level: SwiftyDB offers the choice to carry out any database-related operation synchronously or asynchronously. Which technique you must choose relies on the character of the app you construct. Nevertheless, I’d recommend to make use of the asynchronous technique, as this gained’t block the primary thread whereas a database operation is in progress, and it gained’t have an effect on the person expertise by freezing (even immediately) the UI. However I’m saying once more, it’s completely as much as you.

We’ll use the asynchronous option to save our information in right here. As you’ll see, the respective SwiftyDB technique accommodates a closure that returns the results of the operation. You may learn particulars about that outcome object right here, and truly I’m recommending to take action now.

Let’s implement now our new technique so we will focus on extra about it:

It’s simple to know from the above implementation that we’re going to make use of the identical technique for updating notes too. We make sure that to set the shouldUpdate Bool worth as a parameter to the tactic upfront, after which relying on its worth the asyncDataObject(...) will both create a brand new document or it’ll replace an present one.

Moreover, you see that the second parameter in our technique is a completion handler. We name it with the correct parameter worth, relying on whether or not the saving is profitable or not. I’d recommend you to at all times use completion handlers when you’ve gotten duties operating asynchronously on the background. That approach, you’ll be capable of notify the caller strategies when the background process has completed, and switch any attainable outcomes or information again.

What you see occurring above is what you’ll see occurring in different database-related strategies too. We’ll at all times be checking for an error within the outcome, and we’ll proceed accordingly relying on whether or not there’s any or not. Within the above case if there’s an error, we name our completion handler passing the false worth, which means that the saving was failed. If the other case, we move true to point a profitable operation.

Again to the EditNoteViewController class as soon as once more, let’s get completed with the saveNote() technique. We’ll name the one created proper above, and if the notice saving has been profitable we’ll simply pop the view controller. If there’s an error, then we’ll show a message.

Discover the shouldUpdate variable within the above implementation. It will get the correct worth relying on whether or not the editedNoteID property is nil or not, which means whether or not the notice is being up to date or not.

At this level you’ll be able to run the app and attempt to save new notes. Should you went step-by-step all alongside the way in which up thus far, then you definately’ll be capable of save your notes with none issues.

Loading and Itemizing Notes

With the creation and saving of latest notes being functioning, we will transfer on and make our app able to loading saved notes from the database. The loaded notes are supposed to be listed within the NoteListViewController class. Nevertheless, earlier than we begin working on this class, let’s create first a brand new technique within the Notice.swift file for loading our information.

The SwiftyDB technique that performs the precise loading is the asyncObjectsForType(...), and it really works asynchronously. The outcome will comprise both an error, or a set with notice objects (an array) loaded from the database. Within the first case, we name the completion handler passing the nil worth in order to point to the caller that there was an issue whereas loading the information. Within the second case, we move the Notice objects to the completion handler so we will use them out of this technique.

Let’s head to the NoteListViewController.swift file now. Initially, we should declare an array that can comprise Notice objects (these loaded from the database). It’s going to be the datasource of our tableview (clearly). So, on the high of the category add the next line:

Apart from that, initialize a brand new Notice object as nicely, so we will use the loadAllNotes(...) technique we created earlier:

Time to jot down a extremely easy new technique that can name the one above and cargo all saved objects from the database to the notes array:

Discover that in spite of everything notes get loaded we use the primary thread to reload the tableview. Previous to that in fact we maintain them to the notes array.

The above two strategies are all we’d like for getting the saved notes from the database. That straightforward! Don’t neglect although that the loadNotes() should be known as someplace, and this can occur within the viewDidLoad() technique:

Loading the notes is just not sufficient, as we should use them as soon as they’re fetched. So, let’s begin updating the tableview strategies, beginning by the full variety of rows:

Subsequent, let’s show some notice information to the tableview. To be particular, we’ll show the title, and the creation and modification dates for every notice:

Should you run the app now, all notes that you’ve got created up to now might be listed to the tableview.

An Different Means To Fetch Knowledge

Only a bit earlier we used the asyncObjectsForType(...) technique of the SwiftyDB library to load our notes from the database. This technique returns an array of objects (in our case Notice objects) as you’ve seen, and I think about this to be fairly helpful. Nevertheless, it’s not at all times that helpful to retrieve objects from the database; there are instances the place fetching an array with the precise information values could be extra handy.

SwiftyDB may also help you on that, because it offers another approach for retrieving information. There’s a technique known as asyncDataForType(...) (or dataForType(...) if you wish to make synchronous operations), and it returns a colletion of dictionaries on this kind: [[String: SQLiteValue]] (the place SQLiteValue is any of the allowed datatypes).

You could find extra right here and right here. I go away it for you as an train to counterpoint the Notice class and cargo easy information as nicely, as a substitute of objects solely.

Updating A Notice

One of many options we would like our demo app to have is the aptitude to edit and replace an present notice. In different phrases, we have to current the EditNoteViewController with the small print of a notice that’s being chosen just by tapping to the respective cell, and retailer to the database its modified information as soon as it will get saved once more.

Beginning within the NoteListViewController.swift file, we’d like a brand new property for storing the ID of the chosen notice, so go to the highest of the category and add the next line:

Now, let’s implement the following UITableViewDelegate technique, the place we discover the noteID worth based mostly on the chosen row, after which we carry out the segue to point out the EditNoteViewController:

Within the prepareForSegue(...) technique let’s move the worth of the idOfNoteToEdit to the following view controller:

The half job has been achieved now. Earlier than we change to the EditNoteViewController class and proceed there, let’s make one other fast detour by paying a go to to the Notice class in an effort to implement a easy new technique that can retrieve only a single notice utilizing the ID worth that’s being given with. Right here’s the implementation:

The brand new factor right here is that for first time we use a filter in an effort to apply limitations to the outcomes that might be returned. Utilizing the equal(...) class technique of the Filter class is only a option to set the filter we would like. Don’t miss to go to this hyperlink to see extra methods for making use of filters when fetching information or objects from the database.

By utilizing the filter within the trend proven above, we really ask from SwiftyDB to load solely these data the place the noteID equals to the worth given as a parameter to the tactic. In fact, only one document might be returned as a result of we all know that this discipline is the first key and there’s no option to have multiple data with the identical key.

The discovered outcomes might be returned as an array of Notice objects, so it’s essential to get the primary (and solely) merchandise from that assortment. After that, we undoubtedly should convert the picture information (if exists) to an array of ImageDescriptor objects, and assign it to the photos property. That’s necessary, as a result of if we skip it any photos initially added to the loaded notice gained’t be proven.

On the finish we name the completion handler in line with whether or not the notice fetching was profitable or not. Within the first case we move the fetched object to the completion handler so it may be utilized by the caller, whereas within the second case we simply move nil as there’s no object.

Now we will head to the EditNoteViewController.swift file, and declare and initialize on the similar time a brand new Notice property to the category:

This object might be used firstly for calling the brand new technique we applied above, after which to comprise the loaded information from the database.

We’re nearly to load the notice specified by the editedNoteID property utilizing the loadSingleNote(...) technique. For our function, we’re going to outline the viewWillAppear(_:) technique, and in there we’ll increase our logic.

As you will notice within the following code snippet, all values might be populated correctly as soon as the loadSingleNoteWithID(...) technique returns the fetched notice by way of the completion handler. That implies that we begin setting the notice title, physique, textual content shade, font, and many others, however not solely. If there are photos included to the notice, we’ll be creating photos views for each, utilizing in fact the frames specified within the ImageDescriptor objects.

Don’t miss that after having populated all values, we assign the notice to the editedNote object, so we will use it in a while.

There’s one final step required: To replace the saveNote() technique, so when a notice is being up to date to keep away from creating a brand new Notice object, and to not set a brand new main key and creation date.

So, discover these three strains (contained in the saveNote() technique):

… and change them with the next snippet:

The remainder a part of the tactic stays as is (no less than for now).

Updating the Notes Listing

Should you examined the app up thus far, then you definately would have undoubtedly realized that the notes record is just not up to date whenever you create a brand new notice or whenever you replace an present one. That’s affordable to occur as a result of the app isn’t able to that but, nevertheless on this half we’re about to repair this undesirable behaviour.

As you might guess, we’re going to use the Delegation sample to inform the NoteListViewController class about modifications made to notes within the EditNoteViewController. Our place to begin is to create a brand new protocol within the EditNoteViewController with two required strategies, these proven beneath:

In each instances we offer to the delegate strategies the ID worth of the brand new or edited notice. Now, go to EditNoteViewController class and add the next property:

Lastly, let’s revisit one final time the saveNote() technique. At first find the following line contained in the completion handler block:

Substitute that single line with the next bunch of code:

The correct delegate perform might be known as each time {that a} new notice is created or an present one is being up to date any longer. However what we simply did consists of the half job solely. Let’s change to the NoteListViewController.swift file, and to start with let’s undertake the brand new protocol to the header line of the category:

Subsequent, within the prepareForSegue(...) technique let’s make this class the delegate of the EditNoteViewController. Proper beneath the let editNoteViewController = segue.destinationViewController as! EditNoteViewController line add the following one as proven to this snippet:

Fairly good, because the many of the job has been achieved. What we’re nonetheless lacking is the implementation of the 2 delegate strategies. First, let’s deal with the scenario the place a brand new notice has been created:

As you see, we simply fetch from the database the article specified by the noteID parameter worth, and (if exists) we append it to the notes array and reload the tableview.

Let’s see now the following one:

On this case we first discover the index of the up to date notice within the notes assortment. As soon as that occurs, we load the up to date notice from the database and we change the previous object with the brand new one. By refreshing the tableview, the brand new modification date of the up to date notice might be proven immediately.

Deleting Information

The final main characteristic that’s nonetheless lacking from our demo app is the notice deletion. It’s simple to know that we’d like one final technique applied within the Notice class that might be known as evey time we need to delete a notice, so open the Notice.swift file.

The one new factor on this half is the SwiftyDB technique that performs the precise deletion from the database, as you will notice within the following implementation. Like earlier than, that is yet one more operation executed asynchronously, and we’ve a completion handler to name as soon as the execution is over once more. Lastly, there’s a filter to specify the row that ought to be deleted from the database.

Let’s open the NoteListViewController.swift now, and let’s outline the following UITableViewDataSource technique:

By having added the above technique to our code, every time you swipe in direction of left on a notice cell the default Delete button will seem to the fitting facet. Furthermore, the code that might be executed when the Delete button is tapped is the one which might be outlined within the physique of the if assertion above. Let’s accomplish that:

At first, we discover the correct notice object matching to the chosen cell within the notes assortment. Subsequent, we name our new technique within the Notice class to delete it, and if that operation is profitable we take away the Notice object from the notes array and reload the tableview so we replace the UI.

It was simply that!

And What About Sorting?

Probably you’re questioning how we will type our information whereas fetching them from the database. Sorting is kind of helpful, as it may be based mostly on a number of fields, to be carried out in ascending or descending order and finally change the order of the returned information. For instance, we may type our notes in a approach that the latest modified notes seem to the highest.

Sadly, SwiftyDB doesn’t help information sorting on the time of scripting this tutorial. This can be a drawback certainly, however there’s an answer: To manually type the information whenever you want so. To display this, let’s create one final technique within the NoteListViewController.swift file known as sortNotes(). On this one we’ll use the Swift’s default type() perform:

Since NSDate objects can’t be in contrast straight, we convert them to timestamp values (double values) first. Then we carry out the comparability and we return the outcome. The above code results in notice sorting the place the latest modified notes are within the first positions of the notes array.

The above technique should be known as at any time when the notes array will get modified. First, let’s replace the loadNotes technique as proven subsequent:

Then, we should do the identical to the 2 following delegate strategies:

By operating the app once more now, you’ll see all notes listed on the tableview based mostly on their modification date.

Abstract

Undoubtably, SwiftyDB is a good device that can be utilized in quite a lot of purposes with out a lot effort. It’s actually quick and dependable to what’s made to do, and we will all agree that may cowl a number of wants when a database should be utilized in our apps. On this demo tutorial we went by way of the fundamentals of this library, however that is what you just about have to know. In fact, there’s at all times the official documentation you’ll be able to confer with for additional help. In our instance immediately, and for the sake of the tutorial, we created a database with one desk solely matching to the Notice class. In real-world apps although, you’ll be able to have as many tables as you need, so long as you create the respective fashions in code (let’s say the respective lessons). Personally, I might undoubtedly use SwiftyDB in my tasks, and as a matter of reality, I’m planning to take action. In any case, now about it, you’ve seen the way it works and the way it may be used. It’s as much as you to determine if that is yet one more device in your toolbox or not. Anyway, I hope the time you spent studying isn’t wasted, and also you’ve realized one other new factor, or two. And till our subsequent tutorial comes, have all an exquisite time!

To your reference, you’ll be able to obtain the total mission on GitHub.



[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments