The basic data manipulation tutorial for the data management framework in IOS app _ios

Source: Internet
Author: User

Nsentitydescription is an entity description object that can be used as an analogy to tables in a database, nsentitydescription storing the structure information of a table. These classes are abstract structure classes, do not store the actual information of each piece of data, the specific data is described by the Nsmanagedobject class, we will generally inherit the entity class to Nsmanagedobject.

The XOCDE tool provides a quick entity-class feature, as well as a demo of the class and student entities we started, clicking on the. xcdatamodeld file, clicking on the Editor tab of the navigation bar above the Xcode tool, choosing creat nsmanagedobject Subclass option, select the entity to be instantiated in the pop-up window, as shown in the following figure:

At this point, Xcode will automatically create a file for us that has the declaration of the attributes in each class.

First, create a piece of data

Use the following code to create the data:

Reading data Model files
Nsurl *modelurl = [[NSBundle mainbundle]urlforresource:@ "Model" withextension:@ "MOMD"];
Creating a data Model
Nsmanagedobjectmodel * mom = [[Nsmanagedobjectmodel Alloc]initwithcontentsofurl:modelurl];
Create a persistent storage coordinator
Nspersistentstorecoordinator * PSC = [[Nspersistentstorecoordinator alloc]initwithmanagedobjectmodel:mom];
Database save path
Nsurl * Path =[nsurl fileurlwithpath:[[nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDomainMask, YES) Lastobject] stringbyappendingpathcomponent:@ "Coredataexample.sqlite"];
Add a data sink stack for the persistence Coordinator
/*
The types that can be supported are as follows:
NSString * Const Nssqlitestoretype;//sqlite
NSString * Const Nsxmlstoretype;//xml
NSString * Const nsbinarystoretype;//Binary
NSString * Const nsinmemorystoretype;//Memory
*/
[PSC addpersistentstorewithtype:nssqlitestoretype Configuration:nil Url:path Options:nil Error:nil];
Creating a data management context
Nsmanagedobjectcontext * MOC = [[Nsmanagedobjectcontext alloc]initwithconcurrencytype:nsmainqueueconcurrencytype];
Associate Persistence Coordinator
[MoC SETPERSISTENTSTORECOORDINATOR:PSC];
To create a data object
/*
The creation of the data object is obtained through the entity name
*/
Schoolclass * ModelS = [nsentitydescription insertnewobjectforentityforname:@ "Schoolclass" Inmanagedobjectcontext: MOC];
Setting up the data
Models.name = @ "First Class";
Models.stunum = @60;
For storage
if ([MoC Save:nil]) {
NSLog (@ "new success");
}
NSLog (@ "%@", [[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) Lastobject] stringbyappendingpathcomponent:@ "Coredataexample.sqlite"]);
Found in the printed path, you will find that there is a more than one SQLite file, which has a table to add a piece of data.

Second, query data

In CoreData, query requests are used to query the data, and the query request is managed and maintained by Nsfetchrequest.

Nsfetchrequest mainly provides two aspects of inquiry services:

1. Provide the related function of scope query

2. Provide query result return type and sort related function

The common methods used in Nsfetchrequest are as follows:

A query request to create an entity can be understood as querying in a table
+ (Instancetype) Fetchrequestwithentityname: (nsstring*) EntityName;
Query criteria
@property (Nullable, nonatomic, strong) Nspredicate *predicate;
Sorting data
@property (Nullable, nonatomic, strong) Nsarray<nssortdescriptor *> *sortdescriptors;
Number of data bars returned per query
@property (nonatomic) Nsuinteger fetchlimit;
Set the return type of the query to the data
/*
typedef ns_options (Nsuinteger, Nsfetchrequestresulttype) {
Nsmanagedobjectresulttype = 0x00,
Nsmanagedobjectidresulttype = 0x01,
Nsdictionaryresulttype ns_enum_available (10_6,3_0) = 0x02,
Nscountresulttype ns_enum_available (10_6,3_0) = 0x04
};
*/
@property (nonatomic) Nsfetchrequestresulttype Resulttype;
Set whether the query results contain child entities
@property (nonatomic) BOOL includessubentities;
Set the property value to query
@property (nullable, nonatomic, copy) Nsarray *propertiestofetch;
To query the data in the Schoolclass entity, use the following code:

    //创建一条查询请求
    NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"SchoolClass"];
    //设置条件为 stuNum=60的数据
    [request setPredicate:[NSPredicate predicateWithFormat:@"stuNum == 60"]];
    //进行查询操作
    NSArray * res = [moc executeFetchRequest:request error:nil];
    NSLog(@"%@",[res.firstObject stuNum]);

Initialization of data

The initialization of Nsfetchedresultscontroller requires a query request and a data manipulation context. The code example is as follows:

//遵守协议
@interface ViewController ()<NSFetchedResultsControllerDelegate>
{
    //数据桥接对象
    NSFetchedResultsController * _fecCon;
}
@end

@implementation ViewController

-(void) Viewdidload {
[Super Viewdidload];
Initialize the operation
Nsurl *modelurl = [[NSBundle mainbundle]urlforresource:@ "Model" withextension:@ "MOMD"];
Nsmanagedobjectmodel * mom = [[Nsmanagedobjectmodel Alloc]initwithcontentsofurl:modelurl];
Nspersistentstorecoordinator * PSC = [[Nspersistentstorecoordinator alloc]initwithmanagedobjectmodel:mom];
Nsurl * Path =[nsurl fileurlwithpath:[[nssearchpathfordirectoriesindomains (NSDocumentDirectory, NSUserDomainMask, YES) Lastobject] stringbyappendingpathcomponent:@ "Coredataexample.sqlite"];
[PSC addpersistentstorewithtype:nssqlitestoretype Configuration:nil Url:path Options:nil Error:nil];
Nsmanagedobjectcontext * MOC = [[Nsmanagedobjectcontext alloc]initwithconcurrencytype:nsmainqueueconcurrencytype];
[MoC SETPERSISTENTSTORECOORDINATOR:PSC];
Nsfetchrequest * request = [nsfetchrequest fetchrequestwithentityname:@ "Schoolclass"];
Set data sorting
[Request Setsortdescriptors:@[[nssortdescriptor sortdescriptorwithkey:@ "Stunum" Ascending:yes]];
Initializing data bridging objects
_feccon = [[Nsfetchedresultscontroller alloc]initwithfetchrequest:request Managedobjectcontext:moc Sectionnamekeypath:nil Cachename:nil];
Set up agents
_feccon.delegate=self;
Make a data query
[_feccon Performfetch:nil];
}
@end
The data request object used to initialize the Nsfecthedresultscontroller must have a collation set. In the InitWithFetchRequest:managedObjectContext:sectionNameKeyPath:cacheName: method, if you set the third argument, the partition of the data is performed with the third parameter as the key value. When data changes, a callback to the method is performed through the proxy.

Third, data binding with UITableView

-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) indexPath{
UITableViewCell * cell = [TableView dequeuereusablecellwithidentifier:@ "Cellid"];
if (!cell) {
cell = [[UITableViewCell alloc]initwithstyle:uitableviewcellstylesubtitle reuseidentifier:@ "Cellid"];
}
Get the appropriate data model
Schoolclass * obj = [_feccon Objectatindexpath:indexpath];
Cell.textLabel.text = Obj.name;
Cell.detailTextLabel.text = [NSString stringwithformat:@ "has%@ person", obj.stunum];
return cell;
}
-(Nsinteger) Numberofsectionsintableview: (UITableView *) tableview{
return [_feccon Sections].count;
}
-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (Nsinteger) section{
id<nsfetchedresultssectioninfo> info = [_feccon sections][section];
return [info numberofobjects];

}
The effect is as follows:

Mapping data changes to views

The method to call when the data will change
-(void) Controllerwillchangecontent: (Nsfetchedresultscontroller *) controller
{
Turn on TableView update preprocessing
[[Self tableview] beginupdates];
}
method to call when partitioning data changes
-(void) Controller: (Nsfetchedresultscontroller *) controller didchangesection: (ID <nsfetchedresultssectioninfo >) sectioninfo atindex: (nsuinteger) Sectionindex Forchangetype: (nsfetchedresultschangetype) type
{
Determine the type of behavior
Switch (type) {
Insert new Partition
Case Nsfetchedresultschangeinsert:
[[Self TableView] insertsections:[nsindexset Indexsetwithindex:sectionindex] Withrowanimation: Uitableviewrowanimationfade];
Break
Delete Partition
Case Nsfetchedresultschangedelete:
[[Self TableView] deletesections:[nsindexset Indexsetwithindex:sectionindex] Withrowanimation: Uitableviewrowanimationfade];
Break
Moving partitions
Case Nsfetchedresultschangemove:
Update partitions
Case Nsfetchedresultschangeupdate:
Break
}
}
Proxy for callback when data changes
-(void) Controller: (Nsfetchedresultscontroller *) controller didchangeobject: (ID) anobject Atindexpath: (Nsindexpath * ) Indexpath Forchangetype: (nsfetchedresultschangetype) type Newindexpath: (Nsindexpath *) Newindexpath
{
Switch (type) {
Inserting data
Case Nsfetchedresultschangeinsert:
[[Self TableView] insertrowsatindexpaths:@[newindexpath] withrowanimation:uitableviewrowanimationfade];
Break
Delete data
Case Nsfetchedresultschangedelete:
[[Self TableView] deleterowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationfade];
Break
Update data
Case Nsfetchedresultschangeupdate:
[Self reloaddata];
Break
Moving data
Case Nsfetchedresultschangemove:
[[Self TableView] deleterowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationfade];
[[Self TableView] insertrowsatindexpaths:@[newindexpath] withrowanimation:uitableviewrowanimationfade];
Break
}
}
Proxy for data update end call
-(void) Controllerdidchangecontent: (Nsfetchedresultscontroller *) controller
{
[[Self tableview] endupdates];
}

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.