About the use of CoreData

Source: Internet
Author: User
Tags sqlite database

Some colleagues think CoreData is a can not understand, understand the mysterious East, in fact, iOS local data storage is a SQLite database, a simple database, and this coredata support all stored data, obviously not, stand in my perspective, I do not support the CoreData to save some image data inside, one, if you need to save the picture to convert the image to the data type,
UIImage * image = Info[uiimagepickercontrollereditedimage];
Turn image into data
Self.imagedata = uiimagepngrepresentation (image);
Secondly, there is no stability. Below you explain the usage of coredata.
1. If you are using storyboard now, you can choose to tick at use Core data when you are building a project.

If you write the program in pure code, then you need to manually write the code in the Appdelegate.

. h

@interface Appdelegate:uiresponder <UIApplicationDelegate>

@property (Strong, nonatomic) UIWindow *window;

@property (ReadOnly, Strong, nonatomic) Nsmanagedobjectcontext *managedobjectcontext;
@property (ReadOnly, Strong, nonatomic) Nsmanagedobjectmodel *managedobjectmodel;
@property (ReadOnly, Strong, nonatomic) Nspersistentstorecoordinator *persistentstorecoordinator;

-(void) savecontext;
-(Nsurl *) applicationdocumentsdirectory;

@end

. m

-(void) Savecontext
{
Nserror *error = nil;
Nsmanagedobjectcontext *managedobjectcontext = Self.managedobjectcontext;
if (managedobjectcontext! = nil) {
if ([Managedobjectcontext haschanges] &&![ Managedobjectcontext Save:&error]) {
Replace This implementation with code to handle the error appropriately.
Abort () causes the application to generate a crash log and terminate. You should don't use the This function in a shipping application, although it could be useful during.
NSLog (@ "unresolved error%@,%@", error, [error userInfo]);
Abort ();
}
}
}

#pragma mark-core Data Stack

Returns the managed object context for the application.
If the context doesn ' t already exist, it's created and bound to the persistent store coordinator for the application.
-(Nsmanagedobjectcontext *) Managedobjectcontext
{
if (_managedobjectcontext! = nil) {
return _managedobjectcontext;
}

Nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator];
if (Coordinator! = nil) {
_managedobjectcontext = [[Nsmanagedobjectcontext alloc] init];
[_managedobjectcontext Setpersistentstorecoordinator:coordinator];
}
return _managedobjectcontext;
}

Returns the managed object model for the application.
If the model doesn ' t already exist, it is created from the application ' s model.
-(Nsmanagedobjectmodel *) Managedobjectmodel
{
if (_managedobjectmodel! = nil) {
return _managedobjectmodel;
}
Nsurl *modelurl = [[NSBundle mainbundle] urlforresource:@ "App_7_addressbook" withextension:@ "MOMD"];
_managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl];
return _managedobjectmodel;
}

Returns the persistent store coordinator for the application.
If the coordinator doesn ' t already exist, it's created and the application ' s store added to it.
-(Nspersistentstorecoordinator *) persistentstorecoordinator
{
if (_persistentstorecoordinator! = nil) {
return _persistentstorecoordinator;
}

Nsurl *storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent:@ "App_7_addressbook.sqlite"];

Nserror *error = nil;
_persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:[self Managedobjectmodel]];
if (![ _persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options: Nil Error:&error]) {
NSLog (@ "unresolved error%@,%@", error, [error userInfo]);
Abort ();
}

return _persistentstorecoordinator;
}

#pragma mark-application ' s Documents directory

Returns the URL to the application ' s Documents directory.
-(Nsurl *) applicationdocumentsdirectory
{
return [[[Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask] LastObject ];
}
These are the fundamental cordata that need to be built, without your understanding. Next we should establish an entity that is unfamiliar to cordata technicians who may question why the resume entity? In fact, we store and retrieve data without directly manipulating the cordata, but rather manipulating the entity.

Create a model, which is the entity, and then we create an entity class:

Create a conscious Entity object, and then generate an entity class:

Let's take action on the entity:

@property (Strong, nonatomic) Nsmanagedobjectcontext *managedobjectcontext;

Storage operation via Managedobjectcontext,

First, the managedobjectcontext is initialized;


UIApplication * app = [uiapplication sharedapplication];
ID delegate = [app delegate];
Self.managedobjectcontext = [delegate managedobjectcontext];

1. Then store in the storage area for CoreData,

Such as:

Self.p.number = Self.numberT.text;
Self.p.image = Self.imagedata;

Nserror * ERROR;
if (![ Self.managedobjectcontext Save:&error]) {
NSLog (@ "New Save error:%@", [Error localizeddescription]);
}
To save.

2. When you write a controller that gets data from CoreData,

@property (Strong, nonatomic) Nsmanagedobjectcontext *managedobjectcontext;
@property (Nonatomic,strong) nsfetchedresultscontroller * Fetchedresultscontroller;

The fetchedresultscontroller here is getting data from CoreData,

-(void) Viewdidload {
[Super Viewdidload];

UIApplication *application = [UIApplication sharedapplication];
ID delegate = application.delegate;
Self.managedobjectcontext = [delegate managedobjectcontext];

/*********
Get data from SQLite with CoreData
*********/

Get requests by entity name
Nsfetchrequest *request = [[Nsfetchrequest alloc] Initwithentityname:nsstringfromclass ([Time class])];

Defining grouping and collation rules
Nssortdescriptor *sortdescriptor = [[Nssortdescriptor alloc] initwithkey:@ "Timego" ascending:no];

Add sorting and grouping rules to the request
[Request Setsortdescriptors:@[sortdescriptor]];

Convert the result of the request into data suitable for tableview display
Self.fetchedresultscontroller = [[Nsfetchedresultscontroller alloc] Initwithfetchrequest:request ManagedObjectContext:self.managedObjectContext Sectionnamekeypath:nil Cachename:nil];


Executive Fetchedresultscontroller
Nserror *error;
if ([Self.fetchedresultscontroller Performfetch:&error]) {
NSLog (@ "%@", [Error localizeddescription]);
}
Self.fetchedResultsController.delegate = self;





}

These are coredata basic simple usage, the code is not much written, the important core is these

About the use of CoreData

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.