Core Data simple learning 01, coredata 01

Source: Internet
Author: User

Core Data simple learning 01, coredata 01

Core Data is a framework developed by Apple for Mac and iOS platforms. Using CoreData, You can locally generate the database sqlite and provide the ORM function to convert objects and Data models. manage and operate through Core Data. it can quickly meet the project's data storage needs.
Advantages of CoreData: it can manage the memory reasonably to avoid the trouble and efficiency of using SQL. Because it is a solution provided by Apple, you don't have to worry too much about other problems. my idea is to use it first and then consider other issues. One problem can be solved.
Core Data uses Sqlite by default. So find the. sqlite database file in the sandbox Document folder. Here's a tool to record a good quick open simulator sandbox path: https://github.com/opensim/opensim

1. How to Use CoreData
 

After adding Core Data, you can use AppDelegate. h to generate objects for managing and storing these models. You can add the header file AppDelegate.
After adding Core Data, we create a Data model. When talking about the model, we need to mention the six common objects of Core Data:

1. NSManagedObjectContext
Management object, context, persistent storage model object
2. NSManagedObjectModel
Managed Data Model and Data Structure
3. NSPersistentStoreCoordinator
Database Connection
4. NSManagedObject
Managed Data Records
5. NSFetchRequest
Data Request
6. NSEntityDescription
Table object structure
You also need to know that the. xcdatamodel file is a. momd or. mom file after compilation.

Start

Right-click to add a Core data-> Data Model (if you select use core data directly when creating a project, the. xcdatamodeld is generated by default ).
The selected. xcdatamodeld mainly uses the following:
Entity: Entity (Entity of the model object to be generated, User, Car, Person, etc)
Attributes: Object Attributes
ReaationShips: Relationship
Fetched Properties:


>_<


Multi-table join content can look at: http://www.jianshu.com/p/e9f3b5e0cd19

2. Create Entity Management

Right-click a Core data file and choose NSManagedObject subclass from the shortcut menu. Select Car and Wheel.


QQ20151206-1.png

3. Import the header file AppDelegate. h to start database management.

Main Operations:
// Retrieve the coredata context manager first
AppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContextContext = appDelegate. managedObjectContext ;*
// 1. Save New Data
Car * car = [NSEntityDescription insertNewObjectForEntityForName: @ "Car" inManagedObjectContext: context];
Car. carName = label1.text;
Car. carType = label2.text;
[AppDelegate saveContext];
// 2. query data
NSError * error;
NSFetchRequest * request = [NSFetchRequest new];
NSEntityDescription * entity = [NSEntityDescription entityForName: @ "Car" inManagedObjectContext: context];
[Request setEntity: entity];
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "carName = % @", carName];
[Request setPredicate: predicate];
NSArray * results = [[context executeFetchRequest: request error: & error] copy];
For (Car * car in results ){
 NSLog (@ "% @", car. carName );
}
// 3. Update Data
{
NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription * car = NSEntityDescription entityForName: @ "car" inManagedObjectContext: _ myAppDelegate. managedObjectContext];
[Request setEntity: car];
/// Query Conditions
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "carName = % @", @ "name"];
[Request setPredicate: predicate];
NSError * error = nil;
NSMutableArray * mutableFetchResult = [[_ myAppDelegate. managedObjectContext executeFetchRequest: request error: & error] mutableCopy];
If (mutableFetchResult = nil ){
NSLog (@ "Error: % @", error );
}
NSLog (@ "The count of entry: % I", [mutableFetchResult count]);
For (Car * car in mutableFetchResult ){
Car. carName = @ "name1 ";
...
}
// Save the update. Otherwise, the update is not performed.
[_ MyAppDelegate. managedObjectContext save: & error];
}
// 4. delete data
{
NSFetchRequest * request = [[NSFetchRequest alloc] init];
NSEntityDescription * car = [NSEntityDescription entityForName: @ "Car" inManagedObjectContext: _ myAppDelegate. managedObjectContext];
[Request setEntity: car];
NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "carName = % @", @ "name"];
[Request setPredicate: predicate];
NSError * error = nil;
NSMutableArray * mutableFetchResult = [[_ myAppDelegate. managedObjectContext executeFetchRequest: request error: & error] mutableCopy];
If (mutableFetchResult = nil ){
NSLog (@ "Error: % @", error );
}
NSLog (@ "The count of entry: % I", [mutableFetchResult count]);
For (Car * car in mutableFetchResult ){
[_ MyAppDelegate. managedObjectContext deleteObject: car];
}
If ([_ myAppDelegate. managedObjectContext save: & error]) {
NSLog (@ "Error: % @, % @", error, [error userInfo]);
}
}

  • For more information about conditional queries, see the official documentation:
    Https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html
2. NSFetchRequest common method-setEntity:

Set the data object type (Entity) You want to query)

  • -SetPredicate:
    Set query Conditions
  • -SetFetchLimit:
    Set the maximum number of query objects
  • -SetSortDescriptors:
    Set the sorting method of query results
  • -SetAffectedStores:
    Set the data storage in which queries can be made
    [Request setFetchBatchSize: 500]; // load 500 pieces of data from the database each time to filter data
    [Request setFetchOffset: sizeCount]; // read the cursor offset of the database and read data from the cursor.
    SizeCount = 10;
    [Request setFetchLimit: 10]; // The number of data records to be retrieved each time. 10 means that 10 data records are read from the database each time.
    NSPredicate is used for query and filtering.
    In SQL, WHERE is usually used as the query condition, but NSPredicate can be used as the query condition in COREDATA.
    NSPredicate can not only be used with FetchRequest in COREDATA. It can also be used with NSArray
    A thread uses an NSManagedObjectContext object.
    Using coredata to create a table in the project, it will generate the database by itself, and each table has its own three fields Z_PK, Z_ENT, Z_OPT,
    The primary key of the Z_PK table, which increases progressively from 1 and is unique.
    You can use the primary key to access and obtain objects:

    NSFetchRequest request = [[NSFetchRequest alloc] init];
    [request setEntity:entity];
    [request setResultType:NSManagedObjectIDResultType];
    [request setFetchBatchSize:20];
    NSError
    error = nil;
    NSArray items = [context executeFetchRequest:request error:&error];
    for (NSManagedObjectID
    objectID in items) {
     NSManagedObject* object = [context objectWithID:objectID];
    ...
    }

The index value of the Z_ENT table in xcdatamodel. If there are 6 tables, the value range is [].
Z_OPT indicates the number of operations performed on each data entry. The initial value is 1. If it is added, deleted, modified, and queried, 1 is added.

3. Other records

Easy to view

4. Problem records

When the returned data is fault, you can add this sentence:
[Request setReturnsObjectsAsFaults: NO];

Learning record. If any error occurs, please point it out. Thank you.

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.