Tuesday, June 25, 2024
HomeIOS DevelopmentHow you can Use SwiftData in UIKit Apps

How you can Use SwiftData in UIKit Apps


In iOS 17, Apple launched a brand new framework referred to as SwiftData to exchange the Core Knowledge framework. Earlier, we have now written an introductory tutorial about SwiftData and confirmed you pair SwiftData with SwiftUI.

Whereas there are quite a few studying assets obtainable for utilizing SwiftData with SwiftUI, some readers have talked about that discovering complete guides for integrating SwiftData into UIKit apps will be difficult. On this tutorial, we are going to delve into the method of leveraging the capabilities of SwiftData inside the UIKit framework.

A Fast Introduction about SwiftData

To start out off, let’s take a short tour of the SwiftData framework. It’s essential to grasp that SwiftData shouldn’t be mistaken for a database itself. As a substitute, it’s a framework constructed upon Core Knowledge, particularly developed to help builders in successfully managing and interacting with information saved persistently. Whereas the default persistent retailer utilized by iOS is often the SQLite database, it’s value noting that persistent shops can are available varied kinds. As an illustration, Core Knowledge will also be employed to handle information saved in an area file, reminiscent of an XML file. This flexibility permits builders to decide on essentially the most appropriate persistent retailer for his or her particular necessities.

Whether or not you go for Core Knowledge or the SwiftData framework, each instruments goal to simplify the intricacies of the underlying persistent retailer for builders. Take the SQLite database, for instance. With SwiftData, there’s no must concern your self with establishing database connections or delving into SQL queries to retrieve information data. As a substitute, builders can give attention to using user-friendly APIs and Swift Macros, reminiscent of @Mannequin, to effectively handle information inside their functions. This abstraction permits for a extra streamlined and intuitive information administration expertise.

swiftdata-core-data-model-editor

In case you have used Core Knowledge earlier than, you could do not forget that you need to create an information mannequin (with a file extension .xcdatamodeld) utilizing an information mannequin editor for information persistence. With the discharge of SwiftData, you now not want to try this. SwiftData streamlines the entire course of with macros, one other new Swift characteristic in iOS 17. Say, for instance, you already outline a mannequin class for Music as follows:

To make use of SwiftData, the brand new @Mannequin macro is the important thing for storing persistent information utilizing SwiftUI. As a substitute of constructing the information mannequin with mannequin editor, SwiftData simply requires you to annotate the mannequin class with the @Mannequin macro like this:

That is the way you outline the schema of the information mannequin in code. With this easy key phrase, SwiftData routinely allows persistence for the information class and gives different information administration functionalities reminiscent of iCloud sync. Attributes are inferred from properties and it helps primary worth varieties reminiscent of Int and String.

SwiftData means that you can customise how your schema is constructed utilizing property metadata. You possibly can add uniqueness constraints through the use of the @Attribute annotation, and delete propagation guidelines with the @Relationship annotation. If there are specific properties you don’t want included, you should utilize the @Transient macro to inform SwiftData to exclude them. Right here is an instance:

To drive the information persistent operations, there are two key objects of SwiftData that you have to be accustomed to: ModelContainer and ModelContext. The ModelContainer serves because the persistent backend to your mannequin varieties. To create a ModelContainer, you merely must instantiate an occasion of it.

In UIKit, you may instantiate the context for a given mannequin containers like this:

With the context, you’re able to fetch information. You should use the brand new #Predicate macro to construct predicates. Right here is an instance:

When you outline the factors for fetching, you should utilize the FetchDescriptor and inform the mannequin context to fetch the information.

To insert merchandise within the persistent retailer, you may name the insert technique of the mannequin context and go it the mannequin objects to insert.

Equally, you may delete the merchandise by way of the mannequin context like this:

This serves as a short introduction to SwiftData. When you’re nonetheless feeling not sure about make the most of SwiftData, there’s no want to fret. You’ll acquire a transparent understanding of its utilization as we’ll construct a easy To-do app utilizing UIKit and SwiftData.

Constructing a Easy To-do App with SwiftData and UIKit

I’ve already developed a primary to-do app utilizing UIKit. Nevertheless, the present implementation solely shops the to-do gadgets in reminiscence, which implies the information shouldn’t be persistent. With a purpose to tackle this limitation, our subsequent step is to change the app and swap from utilizing in-memory arrays to leveraging the ability of SwiftData for storing the to-do gadgets in a database. This enhancement will be sure that the to-do gadgets are saved persistently, permitting customers to entry them even after closing the app.

swiftdata-uikit-todo-app

For demo goal, the present model of this app doesn’t present the performance for customers so as to add their very own to-do gadgets. As a substitute, customers can solely add a random to-do merchandise by tapping the “+” button. Nevertheless, customers can nonetheless modify the standing of the prevailing merchandise and delete it by swiping.

Utilizing @Mannequin for the mannequin class

The in-memory model of the app already defines a struct for ToDoItem:

To make use of SwiftData, we are able to convert this struct to class and annotate it with the @Mannequin macro like this:

As you may see, the one factor that we have to do to make a category work with SwiftData is to prefix it with @Mannequin. SwiftData then routinely allows persistence for the information class.

Saving To-Do Gadgets into Database

Within the demo app, we have now the ToDoTableViewController class to deal with the rendering of the to-do desk view, in addition to, the random creation of the to-do gadgets. To handle information with SwiftData, we first create a variable to carry the mannequin container:

Within the viewDidLoad technique, we are able to add the next line of code to instantiate the mannequin container:

For including a random to-do merchandise, the demo app already had a technique named addToDoItem:

We referred to as up the generateRandomTodoItem technique to get a to-do merchandise and append it to the todoItems array. Then we name up the updateSnapshot technique to replace the desk view.

With a purpose to save the to-do merchandise completely, we are able to substitute the code like this:

As a substitute of merely including the to-do merchandise to the array, we make the most of the insert technique of the container’s context to save lots of the merchandise into the inner database.

Fetching Knowledge from Database

The implementation of the fetchToDoItems technique is pending in the mean time. To retrieve information from the database, we have to create an occasion of FetchDescriptor. This permits us to specify the information kind we wish to retrieve and outline any particular search standards if obligatory. By using the FetchDescriptor, we are able to successfully retrieve the specified information from the database. After establishing the fetch descriptor object, we are able to proceed to name the fetch technique of the container’s context and supply the descriptor as an argument. SwiftData will then make the most of this info to retrieve the to-do gadgets accordingly from the database.

Insert the next code snippet to create the fetchToDoItems technique:

As soon as we retrieve all of the to-do gadgets, we have to invoke the updateSnapshot technique to replace the desk view.

Deleting Knowledge from Database

Within the pattern app, we have now a swipe motion for deleting a row merchandise like this:

For now, it solely removes a to-do merchandise from the desk view however not the database. To fully delete the merchandise from database, we have to insert a line of code within the closure:

By calling the delete technique and offering the related merchandise, SwiftData will deal with eradicating the required merchandise from the database, guaranteeing that it’s now not endured in our app’s information storage.

That is how we migrate the to-do app from utilizing in-memory storage to database utilizing SwiftData.

Abstract

By following the steps outlined above, we efficiently migrated the to-do app from utilizing in-memory storage to using a database with the assistance of SwiftData. As demonstrated, the mix of the @Mannequin macro and SwiftData framework simplifies the method of incorporating a database into an app.

We hope that by means of this tutorial, you now possess a clearer understanding of combine SwiftData right into a SwiftUI undertaking and carry out important CRUD (Create, Learn, Replace, Delete) operations. Apple has invested important effort in making persistent information administration and information modeling extra accessible for Swift builders, together with newcomers to the language.

With SwiftData, you’ve gotten a strong device at your disposal to deal with information storage and retrieval effectively. We encourage you to discover additional and leverage the capabilities of SwiftData to reinforce your app growth journey.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments