Example code of realm encapsulation class in swift 3.0
If you have used FMDB or CoreData, try realm. This article mainly introduces the realm encapsulation class in swift 3.0 and shares it with you for your reference, let's take a look.
Thanks for the latest update. @ deepindo
/// Query all the data after sorting, keywords, and whether to sort static func selectScoretByAll in ascending order <T: Object> (_: T. type, key: String, isAscending: Bool)-> Results <T> {return sharedInstance. objects (T. self ). sorted (byProperty: key, ascending: isAscending )}
Import UIKitimport RealmSwiftclass ZYWRealm: NSObject {// name of the realm database static let username = "MY-DB" static let sharedInstance = try! Realm () // -- MARK: Initialize Realm // initialize the encrypted Realm, encrypted Realm only occupies a small amount of additional resources (usually up to 10% slower than normal) static func initEncryptionRealm () {// Description: The following content can be merged, however, in order to display the operation content to the maximum extent, we separately set Realm // to generate a random key var key = Data (count: 64) _ = key. withUnsafeMutableBytes {mutableBytes in SecRandomCopyBytes (kSecRandomDefault, key. count, mutableBytes)} // obtain the configuration file var config = Realm of the encrypted Realm file. configuration (encryptionKey: key )// Use the default directory, but use the user name to replace the default file name config. fileURL = config. fileURL !. DeletingLastPathComponent (). appendingPathComponent ("\ (username). realm") // obtain the parent directory of our Realm file let folderPath = config. fileURL !. DeletingLastPathComponent (). path/*** set to use Realm in background application refresh * Note: The following operations actually disable the NSFileProtection attribute encryption function of the Realm file, downgrade the file protection attribute to a non-strict attribute that allows access to the file even if the device is locked * // remove this directory protection try! FileManager. default. setAttributes ([FileAttributeKey. protectionKey: FileProtectionType. none], ofItemAtPath: folderPath) // apply this configuration to the default Realm database. configuration. defaultConfiguration = config} // initialize the default Realm static func initRealm () {var config = Realm. configuration () // use the default directory, but use the user name to replace the default file name config. fileURL = config. fileURL !. DeletingLastPathComponent (). appendingPathComponent ("\ (username). realm") // obtain the parent directory of our Realm file let folderPath = config. fileURL !. DeletingLastPathComponent (). path // remove this directory protection try! FileManager. default. setAttributes ([FileAttributeKey. protectionKey: FileProtectionType. none], ofItemAtPath: folderPath) // apply this configuration to the default Realm database. configuration. defaultConfiguration = config} // --- MARK: Perform the Realm // write operation static func doWriteHandler (_ clouse: @ escaping ()-> ()) {// The Trailing closure try is used here! SharedInstance. write {clouse () }}// write the static func BGDoWriteHandler (_ clouse: @ escaping ()-> () {try! Realm (). write {clouse () }}// Add a 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) }}// a separate background process writes a set of data static func addListDataAsync <T: Object> (_ objects: [T]) {let queue = DispatchQueue. global (priority: DispatchQueue. globalQueuePriority. default) // Import your items in a background thread queue. async {// Why do you add the following keywords? For more information, see the notes for deleting the Realm file autoreleasepool {// get Realm and table instance let realm = try in this thread! Realm () // batch write operations realm. beginWrite () // The add method supports update. The item object must have a primary key for item in objects {realm. add (item, update: true)} // submit the write transaction to ensure that data can be used in other threads. try! Realm. commitWrite () }}static func addListData <T: Object> (_ objects: [T]) {autoreleasepool {// get Realm and table instance let realm = try in this thread! Realm () // batch write operations realm. beginWrite () // The add method supports update. The item object must have a primary key for item in objects {realm. add (item, update: true)} // submit the write transaction to ensure that data can be used in other threads. try! Realm. commitWrite () }}// delete a data static func delete <T: Object> (_ object: T) {try! SharedInstance. write {sharedInstance. delete (object) }}// delete data in batches static func delete <T: Object> (_ objects: [T]) {try! SharedInstance. write {sharedInstance. delete (objects) }}// delete data in batches static func delete <T: Object> (_ objects: List <T>) {try! SharedInstance. write {sharedInstance. delete (objects) }}// delete data in batches static func delete <T: Object> (_ objects: Results <T>) {try! SharedInstance. write {sharedInstance. delete (objects) }}// delete data in batches static func delete <T: Object> (_ objects: LinkingObjects <T>) {try! SharedInstance. write {sharedInstance. delete (objects) }/// delete all data. Note that the size of the Realm file will not be changed because it will reserve space for fast data storage in the future static func deleteAll () {try! SharedInstance. write {sharedInstance. deleteAll () }}// query the data static func selectByNSPredicate <T: Object> (_: T. type, predicate: NSPredicate)-> Results <T> {return sharedInstance. objects (T. self ). filter (predicate)} // the backend queries the data based on the condition 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 fileurls point to the Realm instance of the Realm file to be deleted, and must be released before the deletion operation is executed. Therefore, you must add autoleasepool when operating the Realm instance. As follows: autoreleasepool {// All Realm usage operations} * // Realm File Deletion operations 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 error }}}}