DEV Community

Khoa Pham
Khoa Pham

Posted on

4

Primary key in Realm

Original post https://github.com/onmyway133/blog/issues/4

Realm is great. But without primary key, it will duplicate the record, like https://github.com/realm/realm-java/issues/2730, http://stackoverflow.com/questions/32322460/should-i-define-the-primary-key-for-each-entity-in-realm, ... So to force ourselves into the good habit of declaring primary key, we can leverage Swift protocol

Create primary constrain protocol like this

protocol PrimaryKeyAware {
  var id: Int { get }
  static func primaryKey() -> String?
}
Enter fullscreen mode Exit fullscreen mode

and conform it in out Realm object

class Profile: Object, PrimaryKeyAware {

  dynamic var firstName: String = ""
  dynamic var lastName: String = ""
  dynamic var id: Int = 0

  override static func primaryKey() -> String? {
    return "id"
  }
}
Enter fullscreen mode Exit fullscreen mode

This way, when using that object in out RealmStorage, we are safe to say that it has a primary key

class RealmStorage<T: Object> where T: PrimaryKeyAware {
  let realm: Realm

  init(realm: Realm = RealmProvider.realm()) {
    self.realm = realm
  }

  func save(_ objects: [T]) {
    try? realm.write {
      realm.add(objects, update: true)
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The usage is like this

let profile = Profile()
let storage = RealmStorage<Profile>()
storage.save([profile])
Enter fullscreen mode Exit fullscreen mode

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
πŸŽ₯ Audio/video file upload with real-time preview
πŸ—£οΈ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
πŸ“€ Export interview's subtitles in VTT format

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay