简体   繁体   中英

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)
    }
}

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.

You can use extensions to add your fetching methods. You add Object subclasses for each entity in your database and then add extensions to each for these methods when needed. Example:

import RealmSwift

// Dog model
class Dog: Object {
    dynamic var name = ""
    dynamic var owner: Person? // Properties can be optional
}

The for your fetching methods:

extension Dog {
    class func fetch(with name: String) -> Dog? {
        return try! Realm().objects(Dog.self).filter("name == %@", name).first
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM