Ios_sn_coredate (i) package use

Source: Internet
Author: User

Read a package CoreData article is very good, there is a basic use of encapsulation, but did not write how with TableView, I use the process of some small twists and turns, I did a demo, we can see the source of some basic use should not be difficult,

Original: Http://blog.csdn.net/pengyuan_d/article/details/40657225?utm_source=tuicool&utm_medium=referral

(1) Create a data model file named Mymodel.xcdatamodeld

(2) Create the Users table, add fields

(3) Create Nsmanagedobject Subclass table entity file

(4) in the users.m file, overwrite the description method

CoreDataDBHelper.h #import <Foundation/Foundation.h> #import <CoreData/CoreData.h>//path of local file storage #define P ATH [Nshomedirectory () stringbyappendingpathcomponent:@ "documents/sqlite.db"] #define MODEL_NAME @ "MyModel" @interfa            Ce coredatadbhelper:nsobject {//1. Data model object Nsmanagedobjectmodel *_managedobjectmodel;            2. Create a local persistent file object Nspersistentstorecoordinator *_persistentstorecoordinator;  3. Manage Data Objects Nsmanagedobjectcontext *_managedobjectcontext;    }//Designed as a single case mode + (Coredatadbhelper *) Sharecoredatadbhelper;    Method of adding data-(BOOL) Insertdatawithmodelname: (NSString *) modelname setattributwithdic: (nsdictionary *) params;           View/* ModelName: Entity object class name predicatestring: Predicate condition identifers: Sort Field Collection Ascending : Whether ascending */-(Nsarray *) Selectdatawithmodelname: (NSString *) modelname predicatestring: (NSS Tring *) predicatestring SorT: (Nsarray *) identifers Ascending: (BOOL) ascending;               Modified-(BOOL) Updatedatawithmodelname: (NSString *) modelname predicatestring: (NSString *) predicatestring    Setattributwithdic: (nsdictionary *) params;     Delete-(BOOL) Deletedatawithmodelname: (NSString *) modelname predicatestring: (NSString *) predicatestring;   @end

COREDATADBHELPER.M

  #import "CoreDataDBHelper.h" @implementation Coredatadbhelper-(instancetype) init {self = [super init]; if (self) {///1. Data Model object Nsurl *modelurl = [[NSBundle Mainbundle] Urlforresource:model_name with          extension:@ "MOMD"];                    _managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl]; 2. Create a local persistent file object _persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:_m          Anagedobjectmodel];                    Set save location for local data nsurl *fileurl = [Nsurl Fileurlwithpath:path]; [_persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:fileUrl options:                    Nil Error:nil];          3. Manage Data Objects _managedobjectcontext = [[Nsmanagedobjectcontext alloc] init];      [_managedobjectcontext Setpersistentstorecoordinator:_persistentstorecoordinator];  } return self; }//Designed as a singleton mode + (COREDATADBHELper *) sharecoredatadbhelper {static Coredatadbhelper *coredatadbhelper = nil;      Static dispatch_once_t Oncetoken;      Dispatch_once (&oncetoken, ^{coredatadbhelper = [[Coredatadbhelper alloc] init];            });  return coredatadbhelper; }//method to add data */params: @{@ "name": @ "Zhang San" @ "Age": @20} */-( BOOL) Insertdatawithmodelname: (NSString *) modelname setattributwithdic: (nsdictionary *) params {nsentit Ydescription *entity = [Nsentitydescription insertnewobjectforentityforname:modelname inManagedObjectContext:_            Managedobjectcontext];          Traversal parameter dictionary for (NSString *key in params) {SEL selector = [self selwithkeyname:key]; if ([entity Respondstoselector:selector]) {[Entity Performselector:selector Withobject:params[key]]          ;            }} [_managedobjectcontext insertobject:entity]; Save to local return [_manaGedobjectcontext Save:nil];           }//View/* ModelName: Entity object class name predicatestring: Predicate condition identifers: Sort Field Collection Ascending : Whether ascending */-(Nsarray *) Selectdatawithmodelname: (NSString *) modelname predicatestring: (NSString *) p Redicatestring Sort: (Nsarray *) identifers Ascending: (BOOL) ASC Ending {//1. Create entity object Nsentitydescription *entity = [Nsentitydescription entityforname:modelname inmanagedobject            Context:_managedobjectcontext];      2. Create a Query object nsfetchrequest *request = [[Nsfetchrequest alloc] init];            Tell the Query object the type of data you want to query [request setentity:entity]; Add Query condition if (predicatestring! = Nil | |      [Predicatestring isequaltostring:@ ""])          {Nspredicate *predicate = [Nspredicate predicatewithformat:predicatestring];      [Request Setpredicate:predicate]; }//3. Set sort Nsmutablearray *sortdescriptors = [NSMUtablearray array]; For (NSString *identifer in identifers) {//Create sort object Nssortdescriptor *sortdescriptor = [[Nssortdesc          Riptor alloc] Initwithkey:identifer ascending:ascending];      Add the Sort object to the array [sortdescriptors Addobject:sortdescriptor];            }//Set the Sort object inside the query object [request Setsortdescriptors:sortdescriptors];  3. Start inquiry return [_managedobjectcontext executefetchrequest:request Error:nil]; }//Modify-(BOOL) Updatedatawithmodelname: (NSString *) modelname predicatestring: (NSString *) predicate String setattributwithdic: (nsdictionary *) params {//Get all required to modify entity object Nsarray *entitys = [Self Selec            Tdatawithmodelname:modelname predicatestring:predicatestring Sort:nil Ascending:no]; Traverse all entity objects for (nsentitydescription *entity in Entitys) {//Modify the properties of the object for (NSString *key in P      Arams) {SEL selector = [self selwithkeyname:key];        if ([entity Respondstoselector:selector]) {[Entity Performselector:selector withobj              Ect:params[key]];        }}} return [_managedobjectcontext Save:nil]; }//Delete-(BOOL) Deletedatawithmodelname: (NSString *) modelname predicatestring: (NSString *) predicatest Ring {//Get all required to modify entity object Nsarray *entitys = [self selectdatawithmodelname:modelname predicatestring:predicatestri            ng Sort:nil Ascending:no]; Traverse all entity objects for (nsentitydescription *entity in Entitys) {//delete object [_managedobjectcontext del                Eteobject:entity];  } return [_managedobjectcontext Save:nil]; }//Back to a set method via a string-(SEL) Selwithkeyname: (NSString *) keyName {nsstring *first = [[KeyName substringtoindex      : 1] uppercasestring];      NSString *end = [KeyName substringfromindex:1]; NSString *selstring = [NSString stringwithformat:@ "set%@%@:", first,end];     Return nsselectorfromstring (selstring);   } @end

Ios_sn_coredata Demo

Ios_sn_coredate (i) package use

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.