Preface
If you have enough FMDB or CoreData, you might as well try realm. This article mainly introduces relevant content about realm encapsulation class in swift 3.0. It is shared for your reference and learning. Let's take a look together below.
Latest update, special thanks to @deepindo
/// Query all data, keywords and whether to ascend after sorting static func selectScoretByAll<T: Object>(_: ,key: String, isAscending: Bool) -> Results<T>{ return ().sorted(byProperty: key, ascending: isAscending) }
import UIKit import RealmSwift class ZYWRealm: NSObject { /// The name of the realm database static let username = "MY-DB" static let sharedInstance = try! Realm() //--MARK: Initialize Realm /// Initializing the encrypted Realm, encrypted Realm will only bring about a small amount of additional resource usage (usually only 10% slower than usual) static func initEncryptionRealm() { // Note: The following contents can be combined, but in order to maximize the display of each operation content, Realm is set separately // Generate random key var key = Data(count: 64) _ = {mutableBytes in SecRandomCopyBytes(kSecRandomDefault, , mutableBytes) } // Get the configuration file for encrypted Realm file var config = (encryptionKey: key) // Use the default directory, but use the username to replace the default filename = !.deletingLastPathComponent().appendingPathComponent("\(username).realm") // Get the parent directory of our Realm file let folderPath = !.deletingLastPathComponent().path /** * Settings can be used in background application refresh * Note: The following operation actually turns off the NSFileProtection property encryption function of Realm file, downgrading the file protection property to a less stringent property that allows access to the file even when the device is locked */ // Unprotect this directory try! ([: ], ofItemAtPath: folderPath) // Apply this configuration to the default Realm database = config } /// Initialize the default Realm static func initRealm() { var config = () // Use the default directory, but use the username to replace the default filename = !.deletingLastPathComponent().appendingPathComponent("\(username).realm") // Get the parent directory of our Realm file let folderPath = !.deletingLastPathComponent().path // Unprotect this directory try! ([: ], ofItemAtPath: folderPath) // Apply this configuration to the default Realm database = config } //--- MARK: Operation Realm /// Do write operations static func doWriteHandler(_ clouse: @escaping ()->()) { // Trailing closure is used here try! { clouse() } } ///Do write operations in the background static func BGDoWriteHandler(_ clouse: @escaping ()->()) { try! Realm().write { clouse() } } /// Add a data static func addCanUpdate<T: Object>(_ object: T) { try! { (object, update: true) } } static func add<T: Object>(_ object: T) { try! { (object) } } /// A separate process in the background writes a set of data static func addListDataAsync<T: Object>(_ objects: [T]) { let queue = (priority: ) // Import many items in a background thread { // Why add the following keywords, see the comments on Realm file deletion autoreleasepool { // Get Realm and table instances in this thread let realm = try! Realm() // Batch write operation () // The add method supports update, the object of item must have a primary key for item in objects { (item, update: true) } // Submit write transactions to ensure data is available in other threads try! () } } } static func addListData<T: Object>(_ objects: [T]) { autoreleasepool { // Get Realm and table instances in this thread let realm = try! Realm() // Batch write operation () // The add method supports update, the object of item must have a primary key for item in objects { (item, update: true) } // Submit write transactions to ensure data is available in other threads try! () } } /// Delete a certain data static func delete<T: Object>(_ object: T) { try! { (object) } } /// Batch delete data static func delete<T: Object>(_ objects: [T]) { try! { (objects) } } /// Batch delete data static func delete<T: Object>(_ objects: List<T>) { try! { (objects) } } /// Batch delete data static func delete<T: Object>(_ objects: Results<T>) { try! { (objects) } } /// Batch delete data static func delete<T: Object>(_ objects: LinkingObjects<T>) { try! { (objects) } } /// Delete all data. Note that the size of the Realm file will not be changed, as it will retain space for the rapid storage of data in the future. static func deleteAll() { try! { () } } /// Query data according to conditions static func selectByNSPredicate<T: Object>(_: , predicate: NSPredicate) -> Results<T>{ return ().filter(predicate) } /// The background querys data based on conditions static func BGselectByNSPredicate<T: Object>(_: , predicate: NSPredicate) -> Results<T>{ return try! Realm().objects().filter(predicate) } /// Query all data static func selectByAll<T: Object>(_: ) -> Results<T>{ return () } //--- MARK: Delete Realm /* Referring to the official documentation, all fileURLs that point to the Realm instances that want to be deleted must be released before the deletion operation is executed. Therefore, when operating Realm instances, autoleasepool needs to be added. as follows: autoreleasepool { //All Realm usage operations } */ /// Realm file deletion operation static func deleteRealmFile() { let realmURL = ! let realmURLs = [ realmURL, ("lock"), ("log_a"), ("log_b"), ("note") ] let manager = for URL in realmURLs { do { try (at: URL) } catch { // Handle errors } } } }
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.