First, the basic concept in-depth
1.NSManagedObjectContext
The managed data context is like a note book
When fetching data from the data persistence layer, it is equivalent to writing these temporary copies of the data on the pad and then modifying the values as you like.
With context, you can add delete changes to the data record Nsmanagedobject, and support undo and redo after the changes are recorded.
Unless you save these data changes, the persistence layer's things will not change.
Usually we bind the Controller class or its subclasses to the Managed object Context Nsmanagedobjectcontext, which makes it easy for us to generate dynamically, get data objects, and so on.
Common methods:
-save: |
To save a data object to a data file |
-objectwithid: |
Querying a data object that specifies the Managed object ID |
-deleteobject: |
Marks a data object for deletion, but does not actually delete the data object until the Context commits the change |
-undo |
Rollback the last step, which is supported by both Undo/redo |
-lock |
Lock, often used for multithreading and creating transactions. The same interface also has:-unlock And-trylock |
-rollback |
Restore Data File contents |
-reset |
Clears the cached Managed Objects. Should only be used when adding or removing persistent Stores |
-undomanager |
Returns the Nsundomanager used by the current Context |
-assignobject:topersistantstore: |
Because the Context can manage data objects from different data files, The purpose of this interface is to specify the data object's storage data file (implemented by specifying Persistantstore) |
-executefetchrequest:error: |
Executes a FETCH data request, returning all matching data objects |
2.NSManagedObject
Managed data records, equivalent to one record in a database
Each of the Nsmanagedobject objects has a global ID (type: Nsmanagedobjectid). Each registered in Nsmanagedobjectcontext.
Nsmanagedobject, which can be queried in context by this global ID.
Each object in the persistent storage layer corresponds to a context-sensitive nsmanagedobject
Common methods:
-entity getting Entities
-objectid Get Nsmanagedobjectid
-valueforkey: Gets the value of the specified property
-setvalue:forkey: Sets the value of the specified property
3.NSFetchRequest
A request to obtain data that executes a query through the context of the managed data, such as
Nsarray *fetchedobjects = [Context executefetchrequest:fetchrequest error:&error];
When querying, you must specify the query entity or entity name to return the query results in nsarray form, and if we do not set any query criteria, all data objects for that entity are returned.
We can use predicates to set query criteria, often saving common Fetch requests to dictionary for reuse.
Nsfetchrequest includes the following sections:
(1) Names of entities (entity)
(2) nspredicate predicate (search keywords or qualifications)
(3) Sorting method (Nsarray *) sortdescriptors
All managed objects (managed object) must be registered in context, and objects obtained through Nsfetchrequest are automatically registered.
If the object to get is already present in the context, then this managed Nsmanagedobject will be returned. Otherwise the context will be looked up from the relevant data source (and may not be found)
For example, the following code is a query created after a specified date and sorts the results of the query by name ContactInfo
nsmanagedobjectcontext * context = [self managedobjectcontext]; Nsmanagedobjectmodel * model = [self managedobjectmodel ]; nsdictionary * entities = [ model entitiesbyname]; nsentitydescription * entity = [entities valueforkey:@ " ContactInfo "]; nspredicate * predicate;predicate = [nspredicate predicatewithformat:@ "CreationDate > %@ ", date]; nssortdescriptor * sort = [[nsortdescriptor alloc] initwithkey:@ "Name"]; nsarray * sortdescriptors = [nsarray arraywithobject: sort]; Nsfetchrequest * fetch = [[nsfetchrequest alloc] init]; [fetch setentity: entity]; [fetch setpredicate: predicate]; [fetch setsortdescriptors: sortdescriptors]; nsarray * results = [context executefetchrequest:fetch error:nil]; [sort release]; [fetch release];
Common methods:
-setentity: |
Set the type of data object you want to query (Entity) |
-setpredicate: |
Set query criteria |
-setfetchlimit: |
Set maximum number of query objects |
-setsortdescriptors: |
To set the sorting method for query results |
-setaffectedstores: |
Set the data store in which you can query |
4.NSPersistentStoreCoordinator
Persistent Data assistant
Core data defines a stack, the persistence storage assistant in the middle, the top of the stack is the context of the managed data, the bottom is the persisted storage layer, the structure
Data is typically read or stored from a data file on disk, which is handled by the underlying read-write. Normally we don't have to deal with it directly, the context already encapsulates the call to it
Common methods:
-addpersistentstoreforurl:configuration:url:options:error: |
Load persisted storage data, the corresponding unload interface is-removepersistentstore:error: |
-migratepersistentstore:tourl:options:withtype:error: |
Migrating the data store, the effect is similar to "Save as", but after the operation succeeds, Data storage before migration is no longer available |
-managedobjectidforurirepresentation: |
Returns the object ID of the data store indicated by the given URL, or nil if no matching data store is found |
-persistentstoreforurl: |
Returns the persistent Store for the specified path |
-urlforpersistentstore: |
Returns the storage path for the specified persistent store |
5.NSManagedObjectModel
A managed data model that describes the entity of the program, its attributes, and the model diagram for the relationship.
Includes the following sections:
(1) Entities (entity)
Corresponding Nsentitydescription object
Equivalent to a table in the database
Entity names (name)
Entity class Name: Name of the Nsmanagedobject subclass
Entity instance: an instance of an Nsmanagedobject object or its subclasses
Nsentitydescription Common methods:
+insertnewobjectforentityforname:inmanagedobjectcontext: Factory method,
Generates the corresponding Nsmanagedobject object according to the given Entity description, and inserts it into the managedobjectcontext.
-managedobjectclassname returns the Nsmanagedobject class name mapped to Entity
-attributesbyname returns the corresponding Attributes in the Entity with the name key.
-relationshipsbyname returns the corresponding relationships in the Entity with the name key.
(2) Attribute (property)
Corresponding Nspropertydescription object
property is an attribute of Entity, which is the equivalent of a column in a database table, or a key in an value-key pair in an XML file.
It can describe entity basic properties (Attribute), relationships between entities (relationship), or query properties (fetched property).
<1> Basic properties of entities (Attributes)
Corresponding Nsattributedescription object
Store basic data, data types include:
String,date,integer (NSString, NSDate, NSNumber)
Relationships between <2> entities (relationships)
Corresponding Nsrelationshipdescription object
Support for one-to-many relationships
<3> Query Properties (fetched property)
Corresponding Nsfetchedpropertydescription object
Returns a qualified data object for a specified entity based on a query predicate
Represents a "weak", single-item relationship (equivalent to a query statement in a database)
6. Persistent storage tier (persistent Stores)
The persistent storage layer is associated with a file or an external database, and most of the actions that access the persisted storage tier are done by the context.
7.NSFetchedResultsController
Used to load part of data in table view
Ii. creating a data model with code
Nsmanagedobjectmodel *managedobjectmodel () { static nsmanagedobjectmodel *momodel = nil; if (Momodel != nil) { return moModel; } moModel = [[NSManagedObjectModel alloc] init]; // create the entity nsentitydescription * runentity = [[nsentitydescription alloc] init]; [runentity setname:@ "Run"]; [runentity setmanagedobjectclassname:@ "Run"]; [moModel setEntities:[NSArray arrayWithObject:runEntity]]; // Add the Attributes Nsattributedescription *dateattribute = [[nsattributedescription alloc] init]; [dateattribute setname:@ "Date"]; [dateattribute setattributetype:nsdateattributetype]; [dateAttribute setOptional:NO]; nsattributedescription *idattribute = [[nsattributedescription alloc] init]; [idattribute setname:@ "ProcessID"]; [idattribute setattributetype:nsinteger32attributetype]; [idattribute setoptional:no]; [idAttribute setDefaultValue:[NSNumber numberWithInteger:-1]]; // Create the validation predicate for the process ID. // The following code is equivalent to Validationpredicate = [nspredicate predicatewithformat:@ "Self > 0"] nsexpression *lhs = [nsexpression expressionforevaluatedobject]; nsexpression *rhs = [nsexpression expressionforconstantvalue:[nsnumber numberwithinteger:0]]; NSPredicate *validationPredicate = [NSComparisonPredicate predicatewithleftexpression:lhs rightExpression:rhs modifier:NSDirectPredicateModifier type:NSGreaterThanPredicateOperatorType options:0]; nsstring *validationwarning = @ "Process ID < 1" ; [idattribute setvalidationpredicates:[nsarray arraywithobject: Validationpredicate] &nbSp; withvalidationwarnings: [nsarray arraywithobject:validationwarning]]; NSArray *properties = [NSArray arraywithobjects: dateattribute, idattribute, nil]; [runentity Setproperties:properties]; // add a localization dictionary nsmutabledictionary *localizationdictionary = [ nsmutabledictionary dictionary]; [localizationdictionary setobject:@ "Date" forkey:@ "Property/date/entity/run"]; [localizationdictionary setobject:@ " Process id " forkey:@" Property/processid/entity/run "]; [localizationdictionary setobject:@ "Process id must not be less than 1" forKey:@ "Errorstring/process id < 1"]; [momodel setlocalizationdictionary:localizationdictionary]; return momodel;}
1) We have created a global model Momodel;
2) and create an entity named run in which the entity corresponding to the ManagedObject class is named run (soon we will create such a class);
3) added two required property:date and ProcessID to run Entity, indicating the runtime and process ID respectively, and set the default process ID to 1;
4) To set the test conditions for ProcessID characteristics: must be greater than 0;
5) Set up a localization description dictionary for the model;
The localization description provides an easy-to-understand description of entity,property,error information, and its available key values are shown in the following table:
Key |
Value |
"Entity/nonlocalizedentityname" |
"Localizedentityname" |
"Property/nonlocalizedpropertyname/entity/entityname" |
"Localizedpropertyname" |
"Property/nonlocalizedpropertyname" |
"Localizedpropertyname" |
"Errorstring/nonlocalizederrorstring" |
"Localizederrorstring" |
Storing data to an XML file
Storage type is Nsxmlstoretype
Nsmanagedobjectcontext *managedobjectcontext () { static nsmanagedobjectcontext *moContext = nil; if (Mocontext != nil) { return moContext; } moContext = [[NSManagedObjectContext alloc] init]; // create a persistent store coordinator, then set the coordinator for the context. Nsmanagedobjectmodel *momodel = managedobjectmodel (); nspersistentstorecoordinator *coordinator = [[nspersistentstorecoordinator alloc] Initwithmanagedobjectmodel:momodel]; [mocontext setpersistentstorecoordinator: coordinator]; // create a new persistent store of the appropriate type. nsstring *store_type = nsxmlstoretype; nsstring *store_filename = @ "Coredatatutorial.xml"; nserror *error = nil; nsurl *url = [ Applicationdocmentdirectory () URLByAppendingPathComponent:STORE_FILENAME]; nspersistentstore *newstore = [coordinator addpersistentstorewithtype: store_type configuration:nil URL:url options:nil error:&error]; if (Newstore == nil) { nslog (@ " store configuration failure\n%@ ", ([Error localizeddescription] != nil) ? [error localizeddescription] : @ "Unknown error"); } return mocontext;}
Iv. Custom Nsmanagedobject Subclasses
For example, the Run.h file
#import <CoreData/NSManagedObject.h> @interface run:nsmanagedobject{nsinteger ProcessID;} @property (retain) nsdate *date; @property (retain) nsdate *primitivedate; @property nsinteger ProcessID; @end
RUN.M file
-(= Mark-mark Getter and setter-=-(=-() Setnilvalueforkey: (NSString * ([Key isequaltostring:=
1) The Access property of date and primitivedate in this class is @dynamic, which indicates that the corresponding setter and getter are dynamically generated during the run time;
2) Here we demonstrate how to correctly manually implement ProcessID setter and getter: in order for Managedobjeccontext to detect ProcessID changes, and to automatically support Undo/redo, We need to tell the system when accessing and changing data Objects, Will/didaccessvalueforkey and Will/didchangevalueforkey.
3) When we set nil to the data object ProcessID, we can capture the situation in Setnilvalueforkey and set the ProcessID to 0;
4) When the data object is inserted into Managedobjectcontext, we set the time in Awakefrominsert to the current time.
Use of Core data (ii)