Top Related Projects
A Cocoa / Objective-C wrapper around SQLite
A type-safe, Swift-language layer over SQLite3.
A toolkit for SQLite databases, with a focus on application development
A fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS
Firebase SDK for Apple App Development
Quick Overview
Realm Swift is a mobile database solution that offers a fast and efficient alternative to SQLite and Core Data. It's designed to be easy to use, allowing developers to work directly with native Swift objects while providing powerful features like real-time synchronization and encryption.
Pros
- Fast performance with minimal overhead
- Simple, intuitive API that works with native Swift objects
- Built-in support for real-time synchronization across devices
- Robust encryption and security features
Cons
- Limited support for complex queries compared to SQL databases
- Steeper learning curve for developers familiar with traditional relational databases
- Potential migration challenges when updating to newer versions
- Some limitations on data model flexibility compared to other solutions
Code Examples
- Defining a Realm object:
class Dog: Object {
@Persisted var name: String = ""
@Persisted var age: Int = 0
@Persisted var breed: String?
}
- Writing to the database:
let realm = try! Realm()
try! realm.write {
let dog = Dog()
dog.name = "Rex"
dog.age = 3
dog.breed = "Labrador"
realm.add(dog)
}
- Querying the database:
let realm = try! Realm()
let youngDogs = realm.objects(Dog.self).filter("age < 5")
- Observing changes:
let realm = try! Realm()
let dogs = realm.objects(Dog.self)
let token = dogs.observe { changes in
switch changes {
case .initial(let results):
// Results are now populated and can be accessed without blocking the UI
case .update(let results, let deletions, let insertions, let modifications):
// Query results have changed
case .error(let error):
// An error occurred while opening the Realm file
}
}
Getting Started
-
Install Realm Swift using CocoaPods. Add to your Podfile:
pod 'RealmSwift'
-
Run
pod install
in your project directory. -
Import RealmSwift in your Swift file:
import RealmSwift
-
Initialize Realm and start using it:
let realm = try! Realm() // Your Realm operations here
Competitor Comparisons
A Cocoa / Objective-C wrapper around SQLite
Pros of FMDB
- Lightweight and simple to use, with a straightforward API
- Direct SQL query support, offering more flexibility for complex queries
- Easier integration with existing SQLite databases
Cons of FMDB
- Requires manual schema management and migrations
- Less performant for large datasets compared to Realm
- Lacks built-in data synchronization capabilities
Code Comparison
FMDB:
let db = FMDatabase(path: "myDatabase.sqlite")
db.open()
db.executeUpdate("INSERT INTO users (name, age) VALUES (?, ?)", withArgumentsIn: ["John", 30])
let results = db.executeQuery("SELECT * FROM users WHERE age > ?", withArgumentsIn: [25])
db.close()
Realm Swift:
let realm = try! Realm()
try! realm.write {
realm.add(User(name: "John", age: 30))
}
let results = realm.objects(User.self).filter("age > 25")
Summary
FMDB is a lightweight SQLite wrapper that offers direct SQL query support and easy integration with existing SQLite databases. However, it requires manual schema management and lacks built-in synchronization. Realm Swift provides a more modern, object-oriented approach with automatic schema management and synchronization capabilities, but may have a steeper learning curve for developers familiar with SQL.
A type-safe, Swift-language layer over SQLite3.
Pros of SQLite.swift
- Lightweight and minimal overhead, suitable for smaller projects
- Direct SQL query support, offering more flexibility for complex queries
- Closer to standard SQLite, making it easier for developers familiar with SQL
Cons of SQLite.swift
- Less abstraction, requiring more manual management of database operations
- Limited built-in support for object-relational mapping (ORM) features
- Potentially more complex setup for advanced features compared to Realm
Code Comparison
SQLite.swift:
let db = try Connection("path/to/db.sqlite3")
try db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
try db.run("INSERT INTO users (name) VALUES (?)", "Alice")
Realm Swift:
let realm = try! Realm()
try! realm.write {
let user = User()
user.name = "Alice"
realm.add(user)
}
Summary
SQLite.swift provides a more traditional SQLite experience with direct SQL support, making it suitable for developers who prefer working closer to the database level. It's lightweight but requires more manual management. Realm Swift offers a higher level of abstraction with built-in ORM features, making it easier to work with objects but potentially less flexible for complex queries. The choice between the two depends on project requirements and developer preferences.
A toolkit for SQLite databases, with a focus on application development
Pros of GRDB.swift
- More flexible SQL support, allowing complex queries and raw SQL execution
- Lighter weight and potentially faster for certain operations
- Better integration with Swift's type system and Codable protocol
Cons of GRDB.swift
- Steeper learning curve, especially for developers not familiar with SQL
- Less comprehensive ecosystem and third-party tooling compared to Realm
- Requires more manual setup and configuration
Code Comparison
GRDB.swift:
try dbQueue.write { db in
try Player(name: "Arthur").insert(db)
}
let players = try dbQueue.read { db in
try Player.fetchAll(db)
}
Realm:
let realm = try! Realm()
try! realm.write {
realm.add(Player(name: "Arthur"))
}
let players = realm.objects(Player.self)
Both GRDB.swift and Realm offer powerful persistence solutions for iOS apps, but they differ in their approach and feature set. GRDB.swift provides more flexibility and control through SQL, while Realm offers a more object-oriented, easy-to-use API. The choice between them depends on the specific needs of your project and your team's expertise.
A fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS
Pros of CocoaLumberjack
- Lightweight and focused on logging functionality
- Highly customizable with various log levels and formatters
- Supports multiple logging destinations (console, file, database)
Cons of CocoaLumberjack
- Limited to logging functionality, not a full database solution
- Requires more setup and configuration for advanced use cases
- May have a steeper learning curve for beginners
Code Comparison
CocoaLumberjack:
import CocoaLumberjack
DDLog.add(DDOSLogger.sharedInstance)
let fileLogger = DDFileLogger()
DDLog.add(fileLogger)
DDLogVerbose("Verbose log message")
DDLogDebug("Debug log message")
DDLogInfo("Info log message")
Realm Swift:
import RealmSwift
let realm = try! Realm()
try! realm.write {
let person = Person()
person.name = "John"
realm.add(person)
}
Summary
CocoaLumberjack is a powerful logging framework for iOS and macOS, offering flexible logging options and destinations. It's ideal for projects that require detailed logging capabilities. Realm Swift, on the other hand, is a mobile database solution that provides easy-to-use persistence functionality. While CocoaLumberjack excels in logging, Realm Swift offers a more comprehensive data management solution. The choice between the two depends on the specific needs of your project, with CocoaLumberjack being better suited for logging-focused applications and Realm Swift for projects requiring robust data persistence.
Firebase SDK for Apple App Development
Pros of Firebase iOS SDK
- Comprehensive suite of tools including authentication, cloud storage, and analytics
- Real-time synchronization capabilities out of the box
- Extensive documentation and community support
Cons of Firebase iOS SDK
- Larger SDK size and potential performance overhead
- Less flexibility for local data storage and offline-first scenarios
- Vendor lock-in to Google's ecosystem
Code Comparison
Firebase iOS SDK:
import Firebase
// Initialize Firebase
FirebaseApp.configure()
// Write data
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["name": "John", "age": 30])
Realm Swift:
import RealmSwift
// Initialize Realm
let realm = try! Realm()
// Write data
try! realm.write {
realm.add(User(name: "John", age: 30))
}
Key Differences
- Firebase iOS SDK offers a cloud-first approach with real-time synchronization, while Realm Swift focuses on local-first storage with optional sync
- Realm Swift provides a more object-oriented database model, whereas Firebase uses a document-based structure
- Firebase iOS SDK includes additional services like authentication and analytics, while Realm Swift is primarily a database solution
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
[!WARNING] We announced the deprecation of Atlas Device Sync + Realm SDKs in September 2024. For more information please see:
For a version of
realm-swift
without sync features, install version 20 or see thecommunity
branch.
About Realm Database
Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & watchOS versions of Realm Swift & Realm Objective-C.
Why Use Realm
- Intuitive to Developers: Realmâs object-oriented data model is simple to learn, doesnât need an ORM, and lets you write less code.
- Built for Mobile: Realm is fully-featured, lightweight, and efficiently uses memory, disk space, and battery life.
- Designed for Offline Use: Realmâs local database persists data on-disk, so apps work as well offline as they do online.
- MongoDB Atlas Device Sync: Makes it simple to keep data in sync across users, devices, and your backend in real-time. Get started for free with a template application and create the cloud backend.
Object-Oriented: Streamline Your Code
Realm was built for mobile developers, with simplicity in mind. The idiomatic, object-oriented data model can save you thousands of lines of code.
// Define your models like regular Swift classes
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
}
class Person: Object {
@Persisted(primaryKey: true) var _id: String
@Persisted var name: String
@Persisted var age: Int
// Create relationships by pointing an Object field to another Class
@Persisted var dogs: List<Dog>
}
// Use them like regular Swift objects
let dog = Dog()
dog.name = "Rex"
dog.age = 1
print("name of dog: \(dog.name)")
// Get the default Realm
let realm = try! Realm()
// Persist your data easily with a write transaction
try! realm.write {
realm.add(dog)
}
Live Objects: Build Reactive Apps
Realmâs live objects mean data updated anywhere is automatically updated everywhere.
// Open the default realm.
let realm = try! Realm()
var token: NotificationToken?
let dog = Dog()
dog.name = "Max"
// Create a dog in the realm.
try! realm.write {
realm.add(dog)
}
// Set up the listener & observe object notifications.
token = dog.observe { change in
switch change {
case .change(let properties):
for property in properties {
print("Property '\(property.name)' changed to '\(property.newValue!)'");
}
case .error(let error):
print("An error occurred: (error)")
case .deleted:
print("The object was deleted.")
}
}
// Update the dog's name to see the effect.
try! realm.write {
dog.name = "Wolfie"
}
SwiftUI
Realm integrates directly with SwiftUI, updating your views so you don't have to.
struct ContactsView: View {
@ObservedResults(Person.self) var persons
var body: some View {
List {
ForEach(persons) { person in
Text(person.name)
}
.onMove(perform: $persons.move)
.onDelete(perform: $persons.remove)
}.navigationBarItems(trailing:
Button("Add") {
$persons.append(Person())
}
)
}
}
Fully Encrypted
Data can be encrypted in-flight and at-rest, keeping even the most sensitive data secure.
// Generate a random encryption key
var key = Data(count: 64)
_ = key.withUnsafeMutableBytes { (pointer: UnsafeMutableRawBufferPointer) in
guard let baseAddress = pointer.baseAddress else {
fatalError("Failed to obtain base address")
}
SecRandomCopyBytes(kSecRandomDefault, 64, baseAddress)
}
// Add the encryption key to the config and open the realm
let config = Realm.Configuration(encryptionKey: key)
let realm = try Realm(configuration: config)
// Use the Realm as normal
let dogs = realm.objects(Dog.self).filter("name contains 'Fido'")
Getting Started
We support installing Realm via Swift Package Manager, CocoaPods, Carthage, or by importing a dynamic XCFramework.
For more information, see the detailed instructions in our docs.
Interested in getting started for free with a template application that includes a cloud backend and Sync? Create a MongoDB Atlas Account.
Documentation
The documentation can be found at mongodb.com/docs/atlas/device-sdks/sdk/swift/. The API reference is located at mongodb.com/docs/realm-sdks/swift/latest/
Getting Help
- Need help with your code?: Look for previous questions with the
realm
tag on Stack Overflow or ask a new question. For general discussion that might be considered too broad for Stack Overflow, use the Community Forum. - Have a bug to report? Open a GitHub issue. If possible, include the version of Realm, a full log, the Realm file, and a project that shows the issue.
- Have a feature request? Open a GitHub issue. Tell us what the feature should do and why you want the feature.
Building Realm
In case you don't want to use the precompiled version, you can build Realm yourself from source.
Prerequisites:
- Building Realm requires Xcode 14.1 or newer.
- Building Realm documentation requires jazzy
Once you have all the necessary prerequisites, building Realm just takes a single command: sh build.sh build
.
You'll need an internet connection the first time you build Realm to download the core binary.
This will produce Realm.xcframework and RealmSwift.xcframework in build/Release/
.
Run sh build.sh help
to see all the actions you can perform (build ios/osx, generate docs, test, etc.).
Contributing
See CONTRIBUTING.md for more details!
Code of Conduct
This project adheres to the MongoDB Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to community-conduct@mongodb.com.
License
Realm Objective-C & Realm Swift are published under the Apache 2.0 license. Realm Core is also published under the Apache 2.0 license and is available here.
Feedback
If you use Realm and are happy with it, please consider sending out a tweet mentioning @realm to share your thoughts!
And if you don't like it, please let us know what you would like improved, so we can fix it!
Top Related Projects
A Cocoa / Objective-C wrapper around SQLite
A type-safe, Swift-language layer over SQLite3.
A toolkit for SQLite databases, with a focus on application development
A fast & simple, yet powerful & flexible logging framework for macOS, iOS, tvOS and watchOS
Firebase SDK for Apple App Development
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot