Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use repository for Realm(ios)

First of all I'm relatively new in ios and have no any experience using mobile dbs.

Wanted to integrate into my app Realm(swift) and wonder if it make sense to have service layer and repository separated or everything just include into the service.

Some example to have a good view.

class UserService {

    var userRepository: UserRepository!

    func findById(userId: String) -> User? {
        return userRepository.findById(userId: userId)
    }
}

class UserRepository {

    private let realm = try! Realm()

    func findById(userId: String) -> User? {
        return realm.object(ofType: User.self, forPrimaryKey: userId)
    }
}
like image 712
mihatel Avatar asked May 04 '17 06:05

mihatel


People also ask

What is realm database iOS?

Realm is a cross-platform mobile database solution designed for mobile applications that you can integrate with your iOS projects. Unlike wrappers around Core Data, Realm doesn't rely on Core Data or even an SQLite back end. This tutorial introduces you to the basic features of Realm on iOS.

Does realm work with SwiftUI?

Realm objects have bindings to SwiftUI controls and, much like toggling the bought property, they already start a realm transaction to write the changes in the database whenever you change those values.


1 Answers

Adding an abstraction layer over the top of database APIs is pretty common. A lot of other developers have wrapped Realm in their own classes in order to hide the API from their business logic code.

There's a couple of considerations in which to be aware:

  1. You need to be carful not to accidentally hurt performance from this. Some users have gone so far as to copy data out of Realm objects into their own objects. This defeats the purpose of Realm's 'zero-copy' mechanism, and so the app now inherently performs worse than using Realm natively.
  2. This is 'pre-emptive work'. You're doing a lot of work up front, just in case you might change your mind down the line. I converted Core Data to Realm in a rather large app a while ago, and it only took a few hours. Trying to architect a 'generic' database solution which you may never end up using sounds like it might not pay off.
  3. You're increasing app complexity. This means more potential for bugs and more rigorous testing would be needed to make sure your API and the database API are in sync.

As long as the new database you'd be moving to consists of managing objects as well (ie Core Data), converting from one database to another isn't usually a lot of work. As such, I'd recommend avoiding unnecessary work until the time when it becomes necessary.

Disclaimer: I work for Realm, but this is my opinion as someone who's shipped personal apps using Core Data, raw SQLite and Realm in the past.

like image 67
TiM Avatar answered Oct 21 '22 04:10

TiM