- Realm, for mobile devices! Replace SQLite and Core Data. Save you weeks of time and thousands of lines of code, and help you create a better user experience. – the Realm’s official website
Advantages of a.
Realm is not built on Core Data, nor is it built on SQLite. It has its own database storage engine, which can efficiently and quickly complete the database construction operation.
Realm is faster than SQLite and much faster than ORM. Simple. Data manipulation is implemented through annotations and object manipulation. Data migration costs are low during version upgrades. Good interaction with libraries such as RXJava, Retrofit, etc.
Ii. Installation method
- Cocoapods (recommended) :
1.[Install CocoaPods 0.39.0 or later] 2. Run pod Repo Update to ensure that CocoaPods can get the latest version 3 of the Realm. In your Podfile, add pod'Realm'To your app target, add pod'Realm/Headers'To your test target; 4. Run pod Install on the TERMINAL. 5. Use the.xcWorkspace generated by CocoaPods to run the project! 6. If you want to use it in Swift, drag the file from Swift/ rlmsupport. Swift to the file navigator of your Xcode project and check to make sure that the *Copy items are availableifThe needed** option has been checked.Copy the code
- Static Framework(Static Library)
Download the latest version of Realm and unzip it. 2. Drag realm. framework from the ios/static/ folder to the file navigator in your Xcode project. Ensure that * * Copy itemsifNeeded ** Select and click **Finish**; 3. Select your project in the Xcode file navigator, then select your application target, and go to the Build Phases** TAB. Add **libc++. TBD ** and **libz.tbd**; 4. If you are using Swift to use Realm, drag the files located in Swift/ rlmsupport. Swift into the file navigator in your Xcode project to make sure that the **Copy items are availableifMen * * is selected.Copy the code
Realm Browser/Database manager
It can be managed by downloading software called Realm Browser from the MAC Appstore
4. The Xcode plug-in
- Quickly create an RLMObject object
Click to download the release zip, decompression after open the plugin/RealmPlugin xcodeproj compile, restart Xcode, command + N, pull down the bottom, there is a Realm of the Model Object icon, click to create RLMObject
5. The API reference
All the classes, all the methods, all the stuff that can be looked up in the API documentation, right
Create a data model
- Create a data model and create parameters
#import <Realm/Realm.h>
#import "ExpandCell_M.h"
typedef enum : NSUInteger {
TransactionDetailButtonTypeAll = 0,
TransactionDetailButtonTypeRecharge,
TransactionDetailButtonTypeDeposit,
TransactionDetailButtonTypeEarnings,
} TransactionDetailButtonType;
@interface ExpandSection_M : RLMObject
/// Whether to hide
@property (nonatomic.assign) BOOL isExpand;
/// Time title
@property (nonatomic.copy) NSString *month;
/ / / judgment type (TransactionDetailButtonType type into NSInteger)
@property (nonatomic.assign) NSInteger DetailType;
/ / / code
@property (nonatomic.assign) NSInteger SectionID;
@end
Copy the code
Matters needing attention:
1.Realm supports the following property types: BOOL, BOOL, int, NSInteger, Long, float, double, CGFloat, NSString, NSDate, and NSData. Tip: Enumerations and structures cannot be stored and need to be cast 2. You can use RLMArray and RLMObject to simulate one-to-many relationships. 3.Realm also supports RLMObject inheritance. Note that Realm ignores objective-C property attributes like nonatomic, atomic, strong, copy, weak, and so on.
So, to avoid misunderstanding, we recommend that you don’t use any property attributes when writing models. However, if you do, these attributes will remain in effect until RLMObject is written to the Realm database. Your custom names for getters and setters will work regardless of whether RLMObject is in or out of a realm.
Vii. Data model customization
Several existing class methods further specify model information:
+ (NSDictionary *)defaultPropertyValues; Can be overridden to provide default values for newly created objects.
+ (NSString *)primaryKey; Can be overridden to set the primary key of the model. Defining primary keys improves efficiency and ensures uniqueness.
+ (NSArray *)ignoredProperties; Can be overridden to prevent realms from storing model properties.
8. Model nesting
//.h
#import <Realm/Realm.h>
@class Person;
// Dog data model
@interface Dog : RLMObject
@property NSString *name;
@property Person *owner;
@end
RLM_ARRAY_TYPE(Dog) / / define RLMArray < Dog >
// Dog owner data model
@interface Person : RLMObject
@property NSString *name;
@property NSDate *birthdate;
// Establish the relationship with RLMArray
@property RLMArray<Dog> *dogs;
@end
RLM_ARRAY_TYPE(Person) / / define RLMArray < Person >
// .m
@implementation Dog
@end // Not yet in use
@implementation Person
@end // Not yet in use
Copy the code
Use Realm for data management
- Method one:
RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^{
// Perform data processing
}];
Copy the code
- Method 2:
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
// Perform data processing
[realm commitWriteTransaction];
Copy the code
Query nine.
1. All data fetching is simple and no copy is created until the data is obtained.
Tips for using RLMResults:
-
Realm’s object query returns an RLMResults object. It contains a series of RLMObject. (Save the type, take out the type)
-
RLMResults has an interface similar to NSArray and the object can be retrieved by index. But unlike NSArray, RLMResult is categorized — it can only hold one RLMObjects type. (Single array type)
-
Getting Objects by category The most basic way to get objects from a realm is [RLMObject allObjects], which returns RLMResults with all RLMObject instances of the queried subclass.
// Default query
RealmRLMResults *dogs = [Dog allObjects]; // Find all 🐶 from the default Realm
// Specify a query
RealmRLMRealm *petsRealm = [RLMRealm realmWithPath:@"pets.realm"]; // Get a specified realm
RealmRLMResults *otherDogs = [Dog allObjectsInRealm:petsRealm]; // Query all dogs in the specified realm
Copy the code
2. Predicate/conditional query
If you’re familiar with NSPredicate, you already know how to query in a realm. RLMObjects, RLMRealm, RLMArray, and RLMResults all provide good methods for querying specific RLMObjects: You just pass in the appropriate NSPredicate instance, predicate string, predicate format string, and you get the RLMObjects instance you want. Just like NSObject.
For example, the following code is an extension of the above. We get instances of all tawn-colored dogs with names beginning with “B” in the default REALM database by calling [RLMObject objectsWhere:].
// Conditional query
RLMResults *tanDogs = [Dog objectsWhere:@"color = 'tan' AND name BEGINSWITH 'B'"];
// Use an NSPredicate object to query
NSPredicate *pred = [NSPredicate predicateWithFormat:@"color = %@ AND name BEGINSWITH %@".@"tan".@"B"];
tanDogs = [Dog objectsWithPredicate:pred];
Copy the code
See Apple’s Predicates Programming Guide for more information on how to create Predicates.
1.Realm supports many common predicates: In comparison, operands can be property names or constants. But at least one of them is an attribute name. ==, <=, <, >=, >, >,! The comparison operators =, and BETWEEN. Boolean attributes can support == and! =. 3. In NSString and NSData properties, we support operators like ==,! =, BEGINSWITH, CONTAINS and ENDSWITH. 4. Realm also supports the following compound operators: AND, OR, NOT Note that we do NOT support aggregate expression types, but we do support the BETWEEN operator, for example:
RLMResults *results = [Person objectsWhere:@"age BETWEEN %@"@ [42.43]].Copy the code
3. Conditional sorting
1. In many cases, we want to get or query results that are sorted by certain criteria. Therefore, RLMArray supports sorting data columns using specified attributes. Realm allows you to specify a sorting requirement and sort by one or more properties. 3. For example, the following code calls [RLMObject objectsWhere:where:] to sort the returned data “dogs” in alphabetical ascending order. :
// Sort tan dogs with names starting with "B" by name
RLMResults *sortedDogs = [[Dog objectsWhere:
@"color = 'tan' AND name BEGINSWITH 'B'"] sortedResultsUsingProperty:@"name" ascending:YES];
Copy the code
4. Chain query
- A unique attribute of the Realm query engine is its ability to do quick and simple chained queries without the hassle of a traditional database. For example, let’s say you want the result sequence for all the tawny puppies and look for the dog whose name starts with “B”. You can send the following request.
RLMResults *tanDogs = [Dog objectsWhere:@"color = 'tan'"];
RLMResults *tanDogsWithBNames = [tanDogs objectsWhere:@"name BEGINSWITH 'B'"];
Copy the code
5. Delete data
- Delete data from a Realm database.
Book *cheeseBook = ... // The Book object stored in a Realm
// Delete an object in a transaction
[realm beginWriteTransaction];
[realm deleteObject:cheeseBook];
[realm commitWriteTransaction];
Copy the code
- Delete all data in the database.
// Delete all data from Realm
[realm beginWriteTransaction];
[realm deleteAllObjects];
[realm commitWriteTransaction];
Copy the code
Ten. Inform
Each time a write transaction completes, a Realm instance is notified to an instance on another thread, which can be responded to by registering a block:
// Observe Realm Notifications
self.token = [realm addNotificationBlock:^(NSString *note, RLMRealm * realm) {
[myViewController updateUI];
}];
Copy the code
The returned Notification token remains active as long as any reference to it points to it. In the class that registers updates, you need to have a strong reference to suppress the token, because once the Notification token is released, the notification is automatically unregistered.
Realm addNotificationBlock:] and Realm removeNotificationBlock:].
Realm configuration
Each user has his or her own different database. After the App starts, the database can be set according to the user’s UID. You can change the default configuration and then access the default database to realize different databases for different users. If the properties change after the model is inserted into the database, version migration is required. The version of APP can be used as the version of the database. When version iteration occurs, the attributes of the model are changed and version migration is realized by changing the version number of APP.
// Migrate and configure basic database data
- (void)setRealmMigration:(NSString *)username{
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// BTLog(@"%@---",config.fileURL);
// Use the default directory, but use the username instead of the default filename
config.fileURL = [[[config.fileURL URLByDeletingLastPathComponent]
URLByAppendingPathComponent:username ? username : @"defalut"]
URLByAppendingPathExtension:@"realm"];
// Apply this configuration to the default Realm database
[RLMRealmConfiguration setDefaultConfiguration:config];
// Set the new schema version. This version number must be higher than the version number previously used (set to 0 if you have never set schema version before)
NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
uint64_t schemaVersion = appVersion.floatValue;
config.schemaVersion = schemaVersion;
// Set the closure, which will be called automatically when opening a Realm database with a version lower than the one set above
config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// So far we have not performed data migration, so oldSchemaVersion == 0
if (oldSchemaVersion < schemaVersion) {
// Don't do anything! Realm detects new and removed properties and automatically updates the database schema on your hard drive}};// Tell Realm to use this new configuration object for the default Realm database
[RLMRealmConfiguration setDefaultConfiguration:config];
// Now that we've told Realm how to handle schema changes, open the file and the migration will be performed automatically
[RLMRealm defaultRealm];
// Location of the realm file
BTLog(@"fileurl===%@",[RLMRealmConfiguration defaultConfiguration].fileURL);
}
Copy the code