The use of Realm databases in iOS mobile terminals

Dinner with a few buddies yesterday, talk to the database, also talked about the advantages and disadvantages of FMDB and CoreData, suddenly found that I only remember about CoreData, in fact, in addition to FMDB and CoreData, and a common database is Realm database.

The FMDB operation is the SQLite database, and the bottom of the CoreData is actually the SQLite database, but CoreData does not need to write the SQL statement, and the CoreData stores the OC object

Realm is also a storage object, and the use of relatively simple. Also can be considered in addition to FMDB and CoreData another choice, encountered not heard of this, you can also install a X

Let’s use the Realm database today to make a simple address book

  • To use the Realm database, the first to import Realm.framework this framework, can be downloaded from the Realm website, I use the realm-objc-2.0.3 version of the download, unzip, the static library in the iOS folder in the static file onto the project
The use of Realm databases in iOS mobile terminals
static library path
  • Then click Targets, select the project, click Build Phases, and add two libraries for libz.tbd and libc++.tbd
The use of Realm databases in iOS mobile terminals
add library
  • Click on the project in the plugin file, run, and then exit XCode, restart XCode, you can install the successful plug-in, we can use plug-ins to automatically generate model classes
The use of Realm databases in iOS mobile terminals
installation plug-in

After you install the successful plug-in, we command + N can find such a thing at the time of the new file

The use of Realm databases in iOS mobile terminals,
, Realm, Model, Object
  • Realm Model Object, as the name suggests, is a Realm database to store the model object, you want to store the data are inherited from this class. So we create a new Realm Model Object file, we build a.H and.M file will automatically help
The use of Realm databases in iOS mobile terminals
RLMObject model file

The function of this model file is quite large

Do the mail list certainly cannot do without tableView, if CoreData and NSFetchedResultsController cooperate with each other, then the Realm is used in the RLMResults of the key
tableView data source is such a thing

ViewController.m

Initialization of the data source: / / - (RLMResults< YFPerson *> resultsArray if (*) {{/ *! _resultsArray) according to the age of the sort / _resultsArray = [[YFPerson allObjects]sortedResultsUsingProperty:@ age ascending:YES] return _resultsArray;}};

When you initialize an array of data sources, you can also set what sorts to order. Here, I sort them by age

Another key class is RLMNotificationToken, which means that when the elements in the database change, the code in the block is called, and it’s very convenient and useful
- (RLMNotificationToken *) notificationToken __weak typeof (self) {weakSelf = self; if (! _notificationToken) {_notificationToken = [self.resultsArray (addNotificationBlock:^ RLMResults< YFPerson *> results * _Nullable, RLMCollectionChange * _Nullable change NSError * _Nullable error) {if (error) {NSLog (@ "open realm database failed.% @". Error); return;} / * if the database change is empty, just refresh the tableView / if (! Change) {weakSelf.tableView} / * [reloadData]; if the change is not empty, then update the tableView data source, and refresh the tableView / * tableView to start the update. [weakSelf.tableView beginUpdates]; tableView [weakSelf.tableView deleteRowsAtIndexPaths:[change / * * / delete data deletionsInSection:0] withRowAnimation:UITableViewRowAnimationTop]; / / because only zeroth groups, so all updates are in zeroth groups of tableView / [weakSelf.tableView insertRowsAtIndexPaths:[change / * add data insertionsInSection:0] withRowAnimation:UITableViewRowAnimationTop]; / * tableView * / [weakSelf.tableView reloadRowsAtIndexPaths:[change modificationsInSection:0] withRowAnimation:UITableViewRowAnimationTop] to refresh the data; / * tableView * / [weakSelf.tableView endUpdates] update end;}];} / * here A print of the sandbox address, then you can see you can see the visual database / NSLog (@ "% @" (NSHomeDirectory)); return _notificationToken;}

We insert data in the block callback, delete data, refresh tableView, do some of these operations. When the database data changes, it will do the corresponding operation, and refresh tableView

On top of this method, print the bin address and use it
  • There is also a key class, that is, the operation of the database, the database has no more than four words: increase, delete, change, check
    , today first talk about the increase and delete it, do an increase of a single contact, and increase the number of contacts
1. add a single contact

The singleton object of RLMRealm is to create instance objects and store them into the Realm database

- (void) addUniquePerson {/ * this class is designed to create the database to write business / * * / [[RLMRealm defaultRealm]beginWriteTransaction]; / * this method is to create an instance of the Realm object, and stored in the database of Realm createInRealm: [RLMRealm defaultRealm] withValue:@[[self / [YFPerson randomName] ([self randomAge]) @ '; / * * / [[RLMRealm defaultRealm]commitWriteTransaction] submitted written business;}

It is necessary to talk about [YFPerson createInRealm:[RLMRealm defaultRealm] withValue:@[[self randomName] ([self randomAge]), @ “; this method, this method is based on KVC, we can pass NSJSONSerialization parsed when setting the value arrays and dictionaries, when introduced into the array, all attributes must be completed, and according to the model of object definition attribute at the time of the order, otherwise it will be wrong

2. increase the number of contacts

Because of time-consuming operations, we must open the child thread

/ * * / add multiple data (void) - addManyPersons {/ * add multiple data is a time-consuming operation, we re open a thread to operate (dispatch_get_global_queue / dispatch_async (0, 0), ^{for (NSUInteger I = 0; I 5; < i++) {/ * cycle internal logic is to add as a single data / [[RLMRealm defaultRealm]beginWriteTransaction] [YFPerson createInRealm:[RLMRealm defaultRealm] withValue:@[[self; randomName] ([self randomAge]), @ "; [[RLMRealm defaultRealm]commitWriteTransaction];}}});
As soon as the method of increase and batch increase is triggered, it is immediately refreshed to tableView, and the order is arranged in ascending order of age, which is set when the array of data sources is initialized
  • In the sideslip deletion, we do a function to delete data, in fact, with the same data added
Method: open the sideslip / / - (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath * indexPath) {/ * delete data, add data and method actually is the same * if (editingStyle = = UITableViewCellEditingStyleDelete) {[[RLMRealm defaultRealm]beginWriteTransaction]; [[RLMRealm defaultRealm]deleteObject:self.resultsArray[indexPath.row]]; [[RLMRealm defaultRealm]commitWriteTransaction];}}

The whole effect is really like this,

The use of Realm databases in iOS mobile terminals
renderings
Then we’ll see where the database is located. What should we do?
  • First, install a
    The use of Realm databases in iOS mobile terminals
    Realm browser
  • Download it in APP Store
  • Then the previously printed sand box address to a “go””
  • The database is stored in the Documents folder and the
    The use of Realm databases in iOS mobile terminals
    database address
  • After you open it with a Realm browser, it’s like this drop, and all the objects you store are inside,
    , The use of Realm databases in iOS mobile terminals,
    , Realm databases

This article source link address
Realm database is also very broad and profound, we discuss together, thank you for your support!