iOS development-The simple use of data persistence realm

Source: Internet
Author: User
Tags knowledge base

Realm is used for data storage just like SQLite, but it has several features that are more useful than other databases:

1. Cross-platform : The vast majority of application development is now developed not only on IOS platforms, but also on the Android platform. It is foolish to design different databases for two platforms, while using the realm database, IOS and Android do not have to consider the architecture of internal data, call the realm provided by the API to complete the exchange of data, to achieve "a database, two platforms seamlessly."

2. easy to use : Core data and SQLite redundancy, complex knowledge and code enough to scare off the vast majority of newly-introduced developers, and switching to Realm, can greatly reduce the learning cost and learning time, so that the application early use of data storage capabilities.

3. Visualization : Realm also provides a lightweight database viewing tool that enables developers to view the contents of a database and perform simple insertions and deletions of data. After all, most of the time, the reason developers use a database is to provide something so-called "knowledge Base."

Here's a look at some of the main class features of realm:

1.RLMRealm : RLMRealm is the core of the framework, the access point we build the database, just like the management object context of Core Data (Managed object contexts). For the sake of simplicity, realm provides a singleton named Defaultrealm, and in this tutorial we'll just use this singleton to do what we need. Of course, we can also import an externally written realm database file, or use the "Memory instance object" (In-memory realm instance) when we don't need to save the data on the hard drive, and you can also use multiple database files at the same time.

2.Rlmobject : This is our custom realm data model. The behavior of creating a data model affects the structure of the database. To create a data model, we only need to inherit rlmobject and then design the properties we want to store.

3. relationship (Relationships) : by simply declaring a property of a rlmobject type in the data model, we can create a "one-to-many" object relationship. Similarly, with Rlmarray we can also create "many-to-one" and "many-to-many" relationships.

4. Write operations Transaction (write transactions) : All operations in the database, such as creating, editing, or deleting objects, must be done in the transaction . A "transaction" is a code snippet located between the Beginwritetransaction () and the commitwritetransaction () operation.

5. query (Queries) : To retrieve information in the database, we need to use the "retrieve" action. The simplest form of retrieval is to send a allobjects () message to a Rlmobject object. If you need to retrieve more complex data, you can also use assertions (predicates), compound queries, and result sorting.

6.RLMResults : This class is the class returned after executing any query request, which contains a series of Rlmobjects objects. Similar to Nsarray, we can use subscript syntax to access it, and we can also determine the relationship between them. Not only that, it also has many more powerful features, including sorting, finding, and so on.

OK, now let's look directly at how to use the simple and practical realm:
1. Create a data Model:

The. h file creates the attributes that you need to save the content for

#import <Realm/Realm.h> @interface person:rlmobject@property nsstring *name @property nsstring *sex; @property int age, @end//This protocol enables typed collections. i.e.://Rlmarray<person>rlm_array_type (person)

. m file no special requirements no operation required

#import "Person.h"@implementation Person//specify default values for properties//+ (Nsdictionary *) defaultpropertyvalues//{//return @{};//}//Specify properties to ignore (Realm won ' t persist these)//+ (Nsarray *) ignoredproperties//{//return @[];//}@end

Controller's. m file

#import "ViewController.h"#import "Person.h"#import "realm.framework/headers/realm.h"@interfaceViewcontroller () {RLMRealm*_customrealm;} @property (Weak, nonatomic) Iboutlet Uitextfield*Name: @property (weak, nonatomic) Iboutlet Uitextfield*sex; @property (weak, nonatomic) Iboutlet Uitextfield*Age ; @property (nonatomic, strong) RLMResults*Locarray, @property (nonatomic, strong) Rlmnotificationtoken*token;@end@implementationViewcontroller- (void) viewdidload {[Super viewdidload]; //additional setup after loading the view, typically from a nib.        /*You can use the default _customrealm = [RLMRealm Defaultrealm]; */    //Create a new Rlmrealm yourselfNsarray *paths =nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES); NSString*pathstr =Paths.firstobject; _customrealm= [RLMRealm realmwithurl:[nsurl fileurlwithpath:[nsstring stringWithFormat:@"%@/%@", Pathstr,@"Custom.realm"]]]; }-(Ibaction) Clickadd: (ID) Sender { person*person =[[Person alloc] init]; Person.name=Self.name.text; Person.sex=Self.sex.text; Person.age=[Self.age.text Intvalue]; //RLMRealm *realm = [RLMRealm Defaultrealm]; //Data Persistence[_customrealm transactionwithblock:^{[_customrealm Addobject:person];        }]; //you can do that .    /*//Add data to Realm via transaction [_customrealm Beginwritetransaction];    [_customrealm Addobject:person];    [_customrealm commitwritetransaction]; */            }-(Ibaction) Clicklog: (ID) Sender {/*Self.locarray = [person Allobjectsinrealm:_customrealm]; */    /** * Sorted by age*/Self.locarray= [[Person Allobjectsinrealm:_customrealm] Sortedresultsusingproperty:@" Age"Ascending:yes]; NSLog (@"%@", Self.locarray); /** * Look for older than 18*/Self.locarray= [[Person Allobjectsinrealm:_customrealm] Objectswhere:@"Age >"]; NSLog (@"%@", Self.locarray); }-(Ibaction) Clickbutton: (ID) Sender { for(Person *personinchSelf.locarray) {NSLog (@"name =%@ Age =%d sex =%@", Person.name,person.age,person.sex); } Person*person =Self.locArray.firstObject; //update objects in a transaction when modified[_customrealm beginwritetransaction]; Person.name=@"Lao Wang";    [_customrealm commitwritetransaction]; }- (void) didreceivememorywarning {[Super didreceivememorywarning]; //Dispose of any resources the can be recreated.}@end

This is the realm of simple additions and deletions, such as the need for in-depth understanding can be self-check information, here did not write more demo, just meet their own needs.

iOS development-The simple use of data persistence realm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.