realm encapsulates class sample code in swift 3.0
- 2020-06-01 11:05:12
- OfStack
preface
If you've had enough of FMDB or CoreData, try realm. This article mainly introduces the content of realm encapsulation class in swift 3.0.
Latest update, special thanks @deepindo
/// Query all data after sorting , Keywords and whether ascending order
static func selectScoretByAll<T: Object>(_: T.Type ,key: String, isAscending: Bool) -> Results<T>{
return sharedInstance.objects(T.self).sorted(byProperty: key, ascending: isAscending)
}
import UIKit
import RealmSwift
class ZYWRealm: NSObject {
/// realm Database name
static let username = "MY-DB"
static let sharedInstance = try! Realm()
//--MARK: Initialize the Realm
/// Initializes in encrypted Realm . encrypted Realm This will result in minimal additional resource usage (usually slower than normal at most) 10% )
static func initEncryptionRealm() {
// Description: The following can be combined, but in order to maximize the display of the content of each operation, it is set separately Realm
// Generate a random key
var key = Data(count: 64)
_ = key.withUnsafeMutableBytes {mutableBytes in
SecRandomCopyBytes(kSecRandomDefault, key.count, mutableBytes)
}
// For encryption Realm File configuration file
var config = Realm.Configuration(encryptionKey: key)
// Use the default directory, but use the user name instead of the default file name
config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm")
// Get our Realm The parent directory of the file
let folderPath = config.fileURL!.deletingLastPathComponent().path
/**
* Settings can be used in background application refresh Realm
* Note: the following operations are actually closed Realm Of the file NSFileProtection Property encryption, which reduces the file protection property to 1 A less restrictive property that allows access to files even when the device is locked
*/
// Unguard this directory
try! FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none], ofItemAtPath: folderPath)
// Apply this configuration to the default Realm In the database
Realm.Configuration.defaultConfiguration = config
}
/// Initialize the default Realm
static func initRealm() {
var config = Realm.Configuration()
// Use the default directory, but use the user name instead of the default file name
config.fileURL = config.fileURL!.deletingLastPathComponent().appendingPathComponent("\(username).realm")
// Get our Realm The parent directory of the file
let folderPath = config.fileURL!.deletingLastPathComponent().path
// Unguard this directory
try! FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none],
ofItemAtPath: folderPath)
// Apply this configuration to the default Realm In the database
Realm.Configuration.defaultConfiguration = config
}
//--- MARK: operation Realm
/// Do write
static func doWriteHandler(_ clouse: @escaping ()->()) { // It's used here Trailing closure
try! sharedInstance.write {
clouse()
}
}
/// Write in the background
static func BGDoWriteHandler(_ clouse: @escaping ()->()) {
try! Realm().write {
clouse()
}
}
/// add 1 The data
static func addCanUpdate<T: Object>(_ object: T) {
try! sharedInstance.write {
sharedInstance.add(object, update: true)
}
}
static func add<T: Object>(_ object: T) {
try! sharedInstance.write {
sharedInstance.add(object)
}
}
/// Background separate process writes 1 Set of data
static func addListDataAsync<T: Object>(_ objects: [T]) {
let queue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default)
// Import many items in a background thread
queue.async {
// Why add the following keywords, see Realm The comment that the file deleted
autoreleasepool {
// Get in this thread Realm And table instance
let realm = try! Realm()
// Bulk write operation
realm.beginWrite()
// add Method supports update . item The object must have a primary key
for item in objects {
realm.add(item, update: true)
}
// Commit write transactions to ensure data is available on other threads
try! realm.commitWrite()
}
}
}
static func addListData<T: Object>(_ objects: [T]) {
autoreleasepool {
// Get in this thread Realm And table instance
let realm = try! Realm()
// Bulk write operation
realm.beginWrite()
// add Method supports update . item The object must have a primary key
for item in objects {
realm.add(item, update: true)
}
// Commit write transactions to ensure data is available on other threads
try! realm.commitWrite()
}
}
/// Delete some data
static func delete<T: Object>(_ object: T) {
try! sharedInstance.write {
sharedInstance.delete(object)
}
}
/// Batch deletion of data
static func delete<T: Object>(_ objects: [T]) {
try! sharedInstance.write {
sharedInstance.delete(objects)
}
}
/// Batch deletion of data
static func delete<T: Object>(_ objects: List<T>) {
try! sharedInstance.write {
sharedInstance.delete(objects)
}
}
/// Batch deletion of data
static func delete<T: Object>(_ objects: Results<T>) {
try! sharedInstance.write {
sharedInstance.delete(objects)
}
}
/// Batch deletion of data
static func delete<T: Object>(_ objects: LinkingObjects<T>) {
try! sharedInstance.write {
sharedInstance.delete(objects)
}
}
/// Delete all data. Pay attention to, Realm The size of the file will not change because it will reserve space for storing data quickly later
static func deleteAll() {
try! sharedInstance.write {
sharedInstance.deleteAll()
}
}
/// Query the data according to the conditions
static func selectByNSPredicate<T: Object>(_: T.Type , predicate: NSPredicate) -> Results<T>{
return sharedInstance.objects(T.self).filter(predicate)
}
/// The background queries the data according to the conditions
static func BGselectByNSPredicate<T: Object>(_: T.Type , predicate: NSPredicate) -> Results<T>{
return try! Realm().objects(T.self).filter(predicate)
}
/// Query all data
static func selectByAll<T: Object>(_: T.Type) -> Results<T>{
return sharedInstance.objects(T.self)
}
//--- MARK: delete Realm
/*
Refer to the official documentation, all fileURL Point to what you want to delete Realm Of the file Realm Instances must be released before the delete operation can be performed.
Therefore, in the operating Realm I need to add it to the instance autoleasepool . The following :
autoreleasepool {
// all Realm Operation operation
}
*/
/// Realm File deletion operation
static func deleteRealmFile() {
let realmURL = Realm.Configuration.defaultConfiguration.fileURL!
let realmURLs = [
realmURL,
realmURL.appendingPathExtension("lock"),
realmURL.appendingPathExtension("log_a"),
realmURL.appendingPathExtension("log_b"),
realmURL.appendingPathExtension("note")
]
let manager = FileManager.default
for URL in realmURLs {
do {
try manager.removeItem(at: URL)
} catch {
// Handling errors
}
}
}
}
conclusion