ObjectBox for Swift 1.4 makes object relations more natural and intuitive for Swift developers. For example, let’s take the teacher-student relation to Swift and how you store objects in the database. Let’s say “Teacher” is a Swift class that has a collection called “students”. Now let’s say we have a new teacher with new students and want to store them in the ObjectBox database. It’s done like this:
This is pretty much standard Swift. A single put command is enough to store all three new objects in the database (sorry for the “try”, Yoda, but you know, IO…). Now let’s see how this works. The students’ property in the Teacher’s class is of type ToMany<Student> and works like any Swift collection. This is because ToMany implements the protocols RandomAccessCollection and RangeReplaceableCollection. Under the hood however, it tracks all changes. Thus, when ObjectBox is instructed to put Yoda in a box, it also knows that two students were added. It also knows that our two Jedi students are new and thus puts them in database too. If you supply students that have been already persisted, it won’t put them. You can also mix new and existing objects.
Version 1.4 does not only bring TooMany (sic) improvements, but also brings a couple of new features, e.g. a bulk-get and read-only stores. You also may have heard of Sync (some kind of teleportation for objects, my young padawan). We’re still working on that, but we started to expose the Sync API with this release. It doesn’t come with any (space consuming) implementation so it’s really about getting early awareness and feedback. A full changelog is available at the docs.
So, time to start your (cocoa) pod again and let us know what you think. May the for… um, OK, that’s getting too many references for one article. One to many.
We speak with Ian Alexander, founder and lead developer at MoodSpace, a beautiful app making mental health exercises accessible to everyone. MoodSpace was released in 2019, and has over 150k+ downloads. The COVID-crises highlights the importance of digital support for wellbeing and saw MoodSpace surge. After trying several databases, Ian settled on ObjectBox because of its high performance and ease of use.
Alyssa: Hi Ian, thank you so much for joining me and for using ObjectBox. Let’s start with the basics about MoodSpace and your role there.
Ian: Hi, Alyssa, thanks for having me. I’m the software developer, founder, and runner of the company – a jack of all trades. MoodSpace is an app that teaches concepts from mental health. There is a massive problem with accessibility to mental health. In the UK, for example, you have something like 1 in 4 people that have some sort of mental health problem, but only 1 in 113 go through therapy and complete it. So our essential goal is to take concepts from therapy and bring them closer to people, teaching them techniques that they can do on an ongoing basis. There’s no end date like in therapy, no waiting list, and it’s a lot easier to use it in places where you wouldn’t necessarily have access to a therapist. In the western world it is much easier to access therapy, still difficult in some ways, but much of the world doesn’t have that benefit. So that’s the goal we’re trying to reach. We started last year, we released the MoodSpace MVP in September, and now we’re going through the next stage of trying to raise our next round of funding – it’s quite exciting.
A: That’s great, congratulations! Can you tell me a bit more about your team?
I: We’re based in the UK, and in terms of the technical side, it’s just me. We also have various other roles: designer, copywriter, and another co-founder who handles much of the business side. But in terms of technical, it is just me for now. Hopefully after we get funding, we’ll be able to expand the technical team..
A: What’s your background, what did you do before MoodSpace?
I: Actually, I was originally a chemical engineer – I worked in oil & gas for a couple of years, but then I taught myself to develop and for the last 5-6 years, I’ve worked across a lot of startups, for example the dating app Once, when they were just starting up, also ITV, and then started on MoodSpace last year. Moodspace has actually existed for quite some time, it started as a hobby project of mine about 5 years ago.
A: There are other mental health apps out there, what makes MoodSpace special?
I: If you look at apps in the space, they’re generally fairly small and limited – they’ll have maybe 4 or 5 exercises. Versus the realm of therapy, which has literally thousands of exercises. Any app that exists at the moment takes just a fraction of a percent of therapy and tries to teach it. Our USP is that we are a very technically minded team, and with new technologies which have come out along with our internal processes, we can make a much bigger app, building something far bigger than what currently exists, much cheaper and far faster. Our USP is strangely, less about the app, and more about our process and the technology that we use to make the app. The tech we will be using is Kotlin Multiplatform, which is a cross platform framework which lets us maintain a single codebase which enables us to build fully native apps with full access to native APIs.
A: It sounds like the app is quite comprehensive – who is your target audience?
I: At the moment, we haven’t hit the product-market-fit stage. We’re still figuring out who the typical user is. We find that the unique art style of our app has helped our growth so far, we often find a lot of people sharing screenshots of the app on social media. So we seem to have hit a niche, but we’re still figuring out what that niche is!
A: Do you have any direct interaction with your users?
I: Mid-last year, I put a survey in the app, so after using it for a certain time users get the survey. There are some questions like who you are, why you are using it, and they gave us way more knowledge about who is using it and what they use it for, which was very helpful. Apart from that though, it is very difficult to know.
A: Yes, it can be very challenging, we’re familiar with that struggle at ObjectBox as well. Switching gears a bit – I’d love to hear a bit more about how and why you ObjectBox.
I: As I mentioned, MoodSpace is about 5 years old, so it’s gone through several databases. One of them was really time consuming to make – it wasn’t ORM based, so you had to write a lot of stuff yourself. Then the next was an ORM called Sugar, but it stopped being developed – it was a side project by someone, so maybe I shouldn’t have used it in the first place (laughs).
I: So then we switched to ObjectBox, and actually the reason we switched was essentially to skip asynchronous code – I’ve always been a frontend developer and what I’ve come across is that asynchronous code makes things very complex, and it means app development takes much longer. Because we had a lot of time constraints and we wanted to develop as much as quickly as possible, I actually wanted to completely skip asynchronous code – which I wouldn’t recommend – but essentially ObjectBox let us do that because it’s very fast. You’d have to have a ton of data in the app, before it would visibly slow it down – and I did a lot of testing around that and it would have needed several years of data before noticeably slowing down the app. So, that was our original reason, perhaps a bit of a strange reason. And we’ve since changed the app so it’s asynchronous, so it won’t slow down any longer, no matter how much data you add in the app. Overall, I like ObjectBox a lot – it’s just simple, very easy to use.
A: What features in your app use the database?
I: Actually everything is in the app, as we don’t have a backend. So we need it to store all the data in the app.
A: Okay, sure. Keeping everything in the app is also practical from a data privacy standpoint. How did you actually find ObjectBox?
I: It was someone I used to work with at Once – they used greenDAO and mentioned that ObjectBox (by the same people) was coming out. I looked into it a little bit and wanted to use it for a while, but it wasn’t I started developing MoodSpace again that I had a chance to.
ObjectBox is very fast, it would have needed several years of data before noticeably slowing down the app. Overall, I like ObjectBox a lot – it’s just simple, very easy to use.
A: Are there any other developer tools that you’re excited about and would want to share with the community?
I: Yes, Kotlin Multiplatform. Having been an Android developer, having used Kotlin for quite some time and having tried cross-platform tools before, I think Kotlin Multiplatform will change the way you make cross platform apps, because it lets you share so much of the code base without sacrificing the native experience. It has the potential of leading to massive cost savings in app development. Maybe in the next year or two I can see it having a huge impact on frontend development across mobile, web, and desktop.
A: What are your big picture goals for MoodSpace? Upcoming milestones? Does ObjectBox help with those at all?
I: Actually, it potentially will, with regards to ObjectBox Sync, which is part of my plan for that app. The app right now is only available on Android, and providing we get our next round of funding, we are going to be adding iOS – where we’ll need some sort of backend. We want to avoid, again, spending much money, and one of ObjectBox Sync, Realm Cloud or Firestore can help us do that – obviously as ObjectBox Sync is nearly ready, we’d want to use that. The main point around that is cost saving because it solves a lot of problems that otherwise we would have to solve ourselves – things like offline access and syncing with an API, that would otherwise be very time intensive.
A: Ian, thank you for your time and sharing more about MoodSpace and working with ObjectBox. We wish you the best of luck with your fundraising round!
Update: newer versions have been released. Check the changelog.
ObjectBox Swift 1.0 is here! Since the first public alpha released 10 months ago, we’ve worked hard and made major changes to put Swift first, tune the performance, and iterate on the API. We hope you love the result and appreciate your feedback.
All of this, to bring you the features you expect from a database, but more importantly – the features that we think delight developers and sets ObjectBox apart from other databases out there. Let’s swiftly (cheap pun intended) dive into ObjectBox Swift 1.0:
Built with Swift in Mind
1
2
3
4
5
6
7
8
9
10
// objectbox: entity
classOlympian{
varid:Id=0
...
}
let store=tryStore(directoryPath:dbURL.path)
let box=store.box(for:Olympian.self)
let olympians:[Olympian]=trybox.all()
let goldMedalist:Olympian=trybox.get(sarahHoefflinId)
ObjectBox isn’t just a database bolted onto Swift. Your database entities are regular Swift classes or structs that you devise. No need to subclass a particular class (as with CoreData’s NSManagedObject), nor to write tedious serialization code. ?
All you need to do is add one property for the unique ID, build your project, and ObjectBox’s code generator will write a little bit of code for you, just like the Swift compiler does for Codable objects. All that’s left then, is to call a simple method like put() on the object to write it out:
1
trybox.put(ruthJebet)
We’ve tried to keep this simplicity throughout the Swift binding, e.g. making it very easy to use any RawRepresentable enum without writing any conversion code.
Automatic Schema Migrations
A common chore with databases is schema migration. ObjectBox takes care of that. If you add a new property or class there are no additional migration steps required. Old objects will keep working, and new objects will be saved with the additional fields. Similarly, adding new classes will add them to the database without any error-prone migration steps.
Moreover, you do not need to maintain a dedicated schema, because your classes and structs are the schema in the first place.
Relations
1
2
3
4
5
6
7
8
classAuthor:Entity{
varid:Id=0
varname:String
varbooks:ToMany<Book>=nil
...
}
amandaPalmer.books.append(theArtOfAsking)
tryamandaPalmer.books.applyToDb()
To ensure ObjectBox knows how to save object references, you use a wrapper class. Either ToOne or ToMany, instead of a straight reference or an array. This lets ObjectBox lazily load the related objects from the database, only when you’re actually accessing a related object.
The Swift 1.0 release brings you our complete set of relations: One-to-many, many-to-many, and their corresponding back-links. ToMany behaves just like any other Swift collection, you can add or remove objects as you please with your familiar methods like append().
Queries
1
2
3
4
5
let query=trybox.query{Author.fname=="Jeaniene"}.build()
let results=tryquery.find()// All Authors matching query.
// All last names of the matching authors:
let names=tryquery.property(Author.lname)
.distinct().findStrings()
Of course ObjectBox lets you perform queries to collect data; either complete objects or individual properties (basic Swift data types).
But with ObjectBox you don’t mess around with query strings or unpack data from cursors. You simply write Swift expressions with function calls and operators you’re already used to.
Also, you get to keep the type-safety guarantees and compile-time checking. So you don’t have to spend hours figuring out why your query doesn’t return the proper results, just to discover you made a typo in a field name in a query string.
1
2
3
4
5
subscription=query.subscribe(){authors,error in
iflet error=error{self.reportError(error);return}
self.authors=authors
self.tableView.reloadData()
}
ObjectBox lets you then operate on these objects, watch a query for changes, retrieve the results, delete the objects matching a query etc. The source code even contains a file that adds Combine support so you can integrate with its pipelines to take advantage of Apple’s newest technology.
Open Source Swift Binding
If you’re curious how things work behind the scenes, feel free to check out the Swift source code. The Swift database source code, as well as our code generator based on Sourcery, are available among other projects through our Github account.
How-to Get Started
It’s a matter of minutes to get started with ObjectBox. Check our setup instructions (based on CocoaPods) and jump right into code with the getting started guide.
Your Feedback. And what’s Next?
As always, we would love to hear your feedback! Do you like ObjectBox as much as we do? We put our hearts in this product and are excited to learn your thoughts: What features are you most excited about, what are we missing?
We haven’t written much about a topic very dear to us: performance. We will cover this in a follow up post. Also, look forward to our ObjectBox Swift 1.0 benchmarks, which we will release soon including the sources.
——
Looking for a fast and simple data synchronization solution?
Vivien: Hi Arne, great to talk with you today. Let’s get started by learning more about you and billiger.de.
Arne: Hi Vivien. I’ve been doing software development for more than 10 years, and API design for the last 5 years. I am currently responsible for mobile development for billiger.de, the most widely used and award-winning price comparison portal in Germany. We’re especially proud of our data security, which was just recently awarded too.
The company behind billiger.de is solute GmbH, which is based in Karlsruhe. They also have a few other brands: shopping.de, an online shopping platform for men and women, and friends communication, an online marketing agency. At billiger.de we’re about 150 employees.
Some of our stats:
300,000+
active daily users on billiger.de
500,000+
app downloads
70 Million
prices in the database
22,500 Shops
comparing 1M products
So clearly, the database and its performance on the server side is very important. Companies update their prices all the time, and on top there are all kinds of vouchers that can be applied. All of these are changing frequently – and you never know who updates their prices when. So, you can see the challenges – from a technical standpoint but also for consumers. It is hard to get the best price.
V: Tell me more about the billiger.de app – why did you decide to go for a native app?
A: Well, to be honest there was an existing native app when I came into the company. But aside from that, it’s essential for UX. We also need some offline capability for features like the notepad function or when users are in the store without an Internet connection and scan barcodes. Once they are online again, the query goes to the cloud – and the user gets his result.
V: So are most of your users on the app? Or rather web?
A: We definitely still have more web users, but user numbers are shifting to mobile more and more. Also, our web users are often one time users only. Our loyalty rate is much higher with app users, so we are trying to increase app installs. We’re seeing that – even on the web – the majority of users are coming from mobile devices. Therefore, we relaunched the website a couple of years ago to be responsive and mobile optimized. So we are focusing more and more on mobile, on both the website and through the app.
V: Why did you need to implement a local database? How is it implemented in your solution?
A: We need data persistence mainly for certain features. We’re still using SQLite, but it’s too much boilerplate code and too little fun. We have been using an ORM on top of SQLite until recently, but it didn’t work well in combination with Proguard on some Android versions anymore. So it resulted in lost data. We’re currently using ObjectBox in the billiger.de Pro version and in a fun new project called PricePretzel, which gives users the best price actively and tracks savings. In these projects, ObjectBox has proven its worth, so we want to migrate the billiger.de app too.
V: Yes, SQLite with an ORM can get very messy. So, why did you choose ObjectBox as the alternative?
A: I looked at several SQLite alternatives and ObjectBox looked interesting. The main decision factors were: ease of integration, stability, and performance. But ease of use and integration were really the most important factors. Stability and enough performance were rather basic necessities. We found ObjectBox really easy to use – we did the migration and everything and because ObjectBox handles that automatically, it was really simple.
We found ObjectBox really easy to use – we did the migration and everything and because ObjectBox handles that automatically, it was really simple.
V: So did performance matter to you at all?
A: For our needs, performance was secondary. Obviously the performance needs to be good enough, but we do not have super high requirements regarding performance.
A: Synchronization obviously is a super interesting feature and we are keeping an eye on it once it is publicly released. From the setup we have, we would need to do it with a connector to our existing database. Currently the web data and app data are separated and we are working on integrating them. So, this needs synchronization.
V: Which other tools do you use in your solution/are you excited about?
A: Retrofit from Square, a networking library, we recommend it to everyone and it works super well with ObjectBox. Both libraries work well together with our business objects. Retrofit fetches the fresh data from our servers and deserializes it into our business objects, which are then persisted with ObjectBox without any additional boilerplate code.
V: billiger.de has over 500.000 downloads and about 4 stars on average – how many daily users does the billiger.de app have? Do you have peak times?
A: Obviously holidays like Christmas and Easter are busier. During the day, early evenings get the most traffic – about 1000-2000 daily active users in the billiger.de app, 200 in our Pro-app, and iOS is similar. As I shared before, we get about 300k daily users on the website.
V: Thanks for sharing, and for talking with me today. Any last words?
A: Thank you for having me! I am looking forward to do more with ObjectBox and am very excited about what comes next!
Today’s 0.9 release is not just a step closer to 1.0, but also an important milestone for us: for the first time, all Swift binding source code is available on GitHub. We’ve also improved performance (again) and added useful features like type converters.
ObjectBox’ lightning-fast database offers a cross-platform C API for language-specific bindings. These bindings provide a thin and nimble wrapper around the C calls and expose ObjectBox functionality in the way that feels most natural to the host language (i.e. Swift).
An open-source binding allows you to make changes to ObjectBox and build it on your own, backport it to older OS or Swift versions, and contribute your changes back to us if you feel so inclined.
Is this the binding I’ve been using all this time?
Although it’s one of our newer language bindings, our Swift binding already has a storied and colorful history. The first Swift binding actually predates our C library and was built directly against the core C++ codebase. As such, it used Objective-C to bridge Swift and C++.
Once we had the C library, we set about eliminating the intermediary and started rewriting the central Objective-C portions as pure Swift on top of the C API. The immediate result when we released ObjectBox for Swift 0.8, was a significant speed-up in write operations due to Swift’s new native UTF-8 strings, and struct support.
But for the open source release, we completed this rewrite, and ObjectBox Swift got even faster:
Not having to bridge to Objective-C meant we could take advantage of Swift’s associated types to resolve class/entity associations instead of a runtime look-up, and eliminate a few duplicated classes necessitated by adding Swift features to Objective-C classes. This in turn allowed removing some unnecessary data copying, which translated directly to increased speed.
While we enjoy a good performance increase as much as the next database developer, we also added new features and fixes, like more query comparison operators for scalar types, and improved behavior when adding properties to an entity.
Property Converters
One major new feature of this release is support for converting simple user-defined types into types the database understands. For example, you can mark any RawRepresentable enum with an annotation to tell ObjectBox how to serialize it. Let’s say we have an enum like
1
2
3
4
5
6
enumOlympicRanking:Int{
caseunset=0
casefirst=100
casesecond=200
casethird=300
}
In your class, you simply add the following annotation:
But of course we also let you work with your own types, or system types. Let’s say you wanted to save a window’s dimensions into your database. You do this using a converter class that implements convert() methods that convert your custom type into one of ObjectBox’s built-in types, and back:
1
2
3
4
5
6
7
8
9
classRectConverter{
staticfunc convert(_box:CGRect)->String{
returnNSCoder.string(for:box)
}
staticfunc convert(_boxString:String?)->CGRect{
guard let boxString=boxStringelse{return.zero}
returnNSCoder.cgRect(for:boxString)
}
}
And then you tell ObjectBox to use that converter using an annotation:
And that’s just a selection of the changes you’ll find in the new open-source release. It contains the entire binding, but also the fork of Sourcery that does its duties as our code generator, and a performance test app. It is faster, more feature-full, and we’ve also squashed some bugs in the binding.
To take a look and get started, simply go to our ObjectBox Swift Git repository, where, in addition to our example application, you can now also find the binding’s source code. Or pull version 0.9 via CocoaPods.
We can’t wait for you to try it out and let us know what you think. Don’t forget to star us if you like it!
Sideloading can cause crashes when used with Android App Bundle. Google is pushing Android developers to publish their apps to Google Play using the new Android App Bundle format. While it comes with benefits, it can also cause your app to crash, if users sideload your app. We’ll explore why this happens and how to fix it.
Android App Bundle (AAB) enables smaller app downloads and updates, increasing the chances that more people will install your app. Developers benefit as well by only having to build a single artifact instead of multiple APKs tailored to various types of devices.
App Bundle and Sideloading
The Play Store will take care of installing the right set of split APKs from the App Bundle for each user’s device configuration. But what happens, if users bypass Google Play and sideload the app? Sideloading has been popular (APKMirror anyone?) to get early access to new versions of an app or to not waste expensive data volume on app downloads (relevant e.g. in various parts of Africa and India).
To explain how sideloading can break your app, let’s first have a look at what Google Play would actually install onto a device when you publish an App Bundle. For this we use bundletool, which Android Studio and Google Play also use, to convert an App Bundle to a set of APKs for a specific device. We’ll build an App Bundle for our ObjectBox Kotlin example app and start an emulator running Android Pie (you can connect a real device as well). Then we can run the command:
If we extract the created connected.apks file (e.g. using unzip or 7-Zip) we find three split APKs. A master APK containing the app’s manifest and all of its code. An x86 APK containing the ObjectBox native library. And a xxhdpi APK with some resources specific for the screen density of the emulator device. Depending on your app (if it uses dynamic feature modules or includes translations) and connected device there might be more or less split APKs. But let’s stick with these three.
Out of the three only the master APK can be installed on its own. The others will fail to install. You can try this yourself by dropping the APKs onto an emulator.
Crashing with LinkageError
Now how does this affect sideloading? You can probably already see the issue: due to lack of awareness that you are using the cool new App Bundle format, users only share the master APK. And as mentioned it installs just fine. However, at runtime your app might access a native library like ObjectBox or some density-specific resources. As these are not part of the master APK your app will crash. Bummer.
If you do not have an Application class or are using content providers check the full documentation. To see this as part of a working app look at the ObjectBox Kotlin example.
Et voilà, instead of your app crashing users will see a dialog asking them to reinstall the app from the Google Play Store (or “an official store” if the library can’t detect it).
How it works
So how does Play Core know if parts of your app are missing? The library is obfuscated – as most Play libraries are. However, decompiling (just open the class files in Android Studio) allows some basic analysis.
At first, it verifies that the device is API level 21 or higher. Older versions of Android do not support split APKs, so no need to check on these devices.
Then it makes sure that the currently installed version of your app actually requires APK splits. After all, you might still distribute your app as a full blown APK to some devices. This check just looks for a special meta-data manifest tag. This tag is added by bundletool (read Play Store) when converting an App Bundle to a set of split APKs (drop the master APK onto Android Studio and check AndroidManifest.xml).
Now that it is certain your app requires multiple APKs for installation it asks PackageManager for the PackageInfo of your app. Starting with API level 21 this has a splitNames property which has the names of any installed split APKs for your app package. If it is empty one or more APKs were not installed and the user is warned to reinstall the app. Straightforward.
Curiously it also warns you, if there is only one entry with an empty name. Please let us know in the comments why you think that is.
And that is it. Make sure to add the Play Core detection if your app is using ObjectBox and App Bundle to avoid sideloading crashes and keep your users happy.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok