The use of the first part of CoreData
Create a project that uses the use CoreData first,
In. Create a table in the Xcdatamodeld file and add properties to the table
To add a relationship to a table,
Next, generate the table model
The properties in the generated Model:user and department are @dynamic
@property have two corresponding words, one is @synthesize and the other is @dynamic. If @synthesize and @dynamic are not written, then the default is @syntheszie var = _var;
The semantics of @synthesize is that if you do not implement setter methods and Getter methods manually, then the compiler will automatically add these two methods to you.
@dynamic tells the compiler that the setter and getter methods of the property are implemented by the user themselves and are not generated automatically. (Of course, for ReadOnly properties, only getter is required). If a property is declared as @dynamic var, then you do not provide the @setter method and the @getter method, the compile time is not a problem, but when the program runs to Instance.var =somevar, due to the lack of setter method will cause the program to crash , or when running to Somevar = Var, the lack of getter method can also cause a crash. Compile-time is no problem, the runtime executes the corresponding method, which is called dynamic binding.
Then the following code is automatically generated in the Appdelegate:
#pragma mark-core Data Stack
@synthesize managedobjectcontext = _managedobjectcontext;
@synthesize Managedobjectmodel = _managedobjectmodel;
@synthesize persistentstorecoordinator = _persistentstorecoordinator;
The exact location stored in the sandbox
-(Nsurl *) applicationdocumentsdirectory {
The directory the application uses to store the Core Data store file. This code uses a directory named Eims. Coredatatest in the application ' s documents directory.
return [[[Nsfilemanager Defaultmanager] urlsfordirectory:nsdocumentdirectory Indomains:nsuserdomainmask] LastObject ];
}
Managed objects
-(Nsmanagedobjectmodel *) Managedobjectmodel {
The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
if (_managedobjectmodel! = nil) {
return _managedobjectmodel;
}
Nsurl *modelurl = [[NSBundle mainbundle] Urlforresource: @CoreDatatest withextension: @momd];
_managedobjectmodel = [[Nsmanagedobjectmodel alloc] initwithcontentsofurl:modelurl];
return _managedobjectmodel;
}
Persistent Storage Coordinator
-(Nspersistentstorecoordinator *) Persistentstorecoordinator {
The persistent store coordinator for the application. This implementation creates and return a coordinator, has added the store for the application to it.
if (_persistentstorecoordinator! = nil) {
return _persistentstorecoordinator;
}
Create the Coordinator and store
_persistentstorecoordinator = [[Nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:[self Managedobjectmodel]];
Nsurl *storeurl = [[Self applicationdocumentsdirectory] urlbyappendingpathcomponent: @CoreDatatest. SQLite];
Nserror *error = nil;
NSString *failurereason = @There is an error creating or loading the application ' s saved data.;
if (![ _persistentstorecoordinator addpersistentstorewithtype:nssqlitestoretype configuration:nil URL:storeURL options: Nil Error:&error]) {
Report any error we got.
Nsmutabledictionary *dict = [Nsmutabledictionary dictionary];
Dict[nslocalizeddescriptionkey] = @Failed to initialize the application ' s saved data;
Dict[nslocalizedfailurereasonerrorkey] = Failurereason;
Dict[nsunderlyingerrorkey] = error;
Error = [Nserror errorwithdomain: @YOUR_ERROR_DOMAIN code:9999 userinfo:dict];
Replace this 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 ();
}
return _persistentstorecoordinator;
}
Managed context
-(Nsmanagedobjectcontext *) Managedobjectcontext {
Returns the managed object context for the application (which are already bound to the persistent store coordinator for The application.)
if (_managedobjectcontext! = nil) {
return _managedobjectcontext;
}
Nspersistentstorecoordinator *coordinator = [self persistentstorecoordinator];
if (!coordinator) {
return nil;
}
_managedobjectcontext = [[Nsmanagedobjectcontext alloc] init];
[_managedobjectcontext Setpersistentstorecoordinator:coordinator];
return _managedobjectcontext;
}
#pragma mark-core Data Saving support
-(void) Savecontext {
Nsmanagedobjectcontext *managedobjectcontext = Self.managedobjectcontext;
if (managedobjectcontext! = nil) {
Nserror *error = 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 ();
}
}
}
This code knows the specific role is good, if you want to manually build up CoreData files, you can manually write
Here is the specific operation in Viewcontroller,
First, appdelegate and user,department header files are introduced.
Add in Viewcontroller
@property (Strong, nonatomic) Appdelegate *myappdelegate;
And then
Specific operation,
Add to:
User*user = (user*) [nsentitydescription insertnewobjectforentityforname: @User inmanagedobjectcontext: Self.myAppDelegate.managedObjectContext];
[User Setname:_nametextfield.text];
[User Setage:[nsnumber Numberwithinteger:[_agetextfield.text IntegerValue]];
[User Setsex:_sextextfield.text];
Nserror*error;
BOOL issavesuccess = [Myappdelegate.managedobjectcontext save:&error];//Save (easy to forget)
if (!issavesuccess) {
NSLog (@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat: @Error:%@,error];
}else{
NSLog (@Save successful!);
_attentiontextview.text = @Save successful!;
}
Inquire:
Data request (Request): command set
Nsfetchrequest*request = [[Nsfetchrequest alloc]init];
Nsentitydescription (Entity description): Table
Nsentitydescription*user = [nsentitydescription entityforname: @Department inmanagedobjectcontext: Myappdelegate.managedobjectcontext];
[Request Setentity:user];
Nserror*error;
Nsarray*mutablefetchresult = [Myappdelegate.managedobjectcontext
Executefetchrequest:request error:&error];
if (Mutablefetchresult = = nil) {
NSLog (@Error:%@,mutablefetchresult);
}
NSLog (@the Count of Entry:%lu,[mutablefetchresult Count]);
Nsstring*str = @;
For (Department*user in Mutablefetchresult) {
NSLog (@name:%@------age:%@-------Sex:%@,user.name,user.age,user.sex);
str = [str stringbyappendingformat: @name:%@------age:%@-------sex:%@---depart:%@, user.name,user.age,user.sex, User.userrelationship.departmentname];
str = [str stringbyappendingformat: @name:%@------, user.departmentname];
}
NSLog (@str:%@,STR);
Update:
Nsfetchrequest Data Request (Request): command set
Nsfetchrequest*request = [[Nsfetchrequest alloc]init];
Nsentitydescription (Entity description): Table
Nsentitydescription*user = [nsentitydescription entityforname: @User inmanagedobjectcontext: Myappdelegate.managedobjectcontext];
[Request Setentity:user];
Set query condition Nspredicate (predicate): query statement
Nspredicate*predicate = [Nspredicate predicatewithformat: @name = =%@, @lisi];
[Request Setpredicate:predicate];
Nserror*error;
Nsarray * Mutablfetchresult = [Myappdelegate.managedobjectcontext executefetchrequest:request error:&error];
if (Mutablfetchresult = = nil) {
NSLog (@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat: @Error:%@,error];
}
NSLog (@the Count of Entry:%lu,[mutablfetchresult Count]);
For (User*user in Mutablfetchresult) {
[user Setage:[nsnumber numberwithinteger:999];
}
Determine if the modification was successful
BOOL issavesuccess = [Myappdelegate.managedobjectcontext save:&error];//Save (easy to forget)
if (!issavesuccess) {
NSLog (@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat: @Error:%@,error];
}else{
NSLog (@update successful!);
_attentiontextview.text = @update successful!;
}
Delete:
Data request (Command set)
Nsfetchrequest*request = [[Nsfetchrequest alloc]init];
Entity Description (table)
Nsentitydescription*user = [nsentitydescription entityforname: @Department inmanagedobjectcontext: Myappdelegate.managedobjectcontext];
[Request Setentity:user];
Set query criteria
nspredicate* predicate = [Nspredicate predicatewithformat: @departmentname = =%@,@ Public sector];
[Request Setpredicate:predicate];
Nserror*error;
Nsarray*mutablefetchresult = [Myappdelegate.managedobjectcontext executefetchrequest:request error:&error];
if (Mutablefetchresult = = nil) {
NSLog (@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat: @Error:%@,error];
}
NSLog (@mutableFetchResult%lu,[mutablefetchresult count]);
For (User*user in Mutablefetchresult) {
[Myappdelegate.managedobjectcontext Deleteobject:user];
}
Determine if Delete succeeded
BOOL isdeletesuccess = [Myappdelegate.managedobjectcontext save:&error];//Save (easy to forget)
if (!isdeletesuccess) {
NSLog (@Error:%@,error);
_attentiontextview.text = [NSString stringWithFormat: @Error:%@,error];
}else{
NSLog (@delete successful!);
_attentiontextview.text = @delete successful!;
}
CoreData is not strictly said to be a package of SQLite database, but also can use other databases, do not have to use sqlite3, of course, the benefits of CoreData is very much, efficient, brief, can save at least 50% of the code, entries fresh
For iOS developers, using core data is a must-have skill. Without it, many apps will not exist. When searching around the Internet for core Data learning tutorials, you can easily be intimidated by a variety of terminology. In fact, most of the learning tutorials assume that you already know these terms, and if you don't understand them, you're going to get into confusion. So first you need to know the key terminology