iOS Development Learning notes-data persistence core

Source: Internet
Author: User
Tags sqlite database

The Coredate of data persistence

A About Core Data

Core data is a framework that Apple provides for data persistence, rather than a database that provides the functionality of object-relational mapping "ORM" (Transforming objects into data and restoring data saved in the database to objects).

Although the underlying operation is similar to SQLite, it does not directly write the SQL statement, and only the entity record is taken out and then decomposed to get a property.

Types that Core data can store: SQLite database, XML, binary, custom data types

Under normal circumstances, the data of Core is under the document under the sandbox, and you can use Masesqlite to view

Core Data Key class

Nsmanagedobjectmodel (Managed object model)

Database all tables or data structures containing the definition information for each entity

Role: Adding attributes to entities, establishing relationships between attributes

How to: View Editor , or code

Nsmanagedobjectcontext (Managed object context)

Manipulating the actual content (Operation persistence layer)

Functions: Inserting, updating, querying, deleting data

Nsmanagedobject (managed data Object)

Equivalent to a record in the database

Nspersistentstorecoordinator (persistent storage coordinator)

A connector equivalent to a database

Role: Set the name, location, storage, and storage time of the data store

Nsfetchrequest ( request to get data)

A query statement equivalent to a database

Nspredicate (predicate)

filter criteria for querying data

Nsentitydescription (Entity description)

Description of the entity structure used to create the object

Keywords: entities: Entity (equivalent to table, first capitalization ) attribute: Attrubute (equivalent to field, lowercase first letter ) Association: A table can be associated with a table .

Q: What if I need to store picture attachments?

A: Save the attachment first, then save the address to the data table.

Two Core Data uses configuration

To use the Coredate must be configured first, it is best to use the new project to choose using Core Data, will save a lot of configuration code, you can use the visual configuration, you can also use code creation.

The main steps are:

1. Select Use Core Data when creating the project

2. Create a new Entity (set table properties and associations)

Configuration details see:: Hong Chong College ? coredata(i)-Introduction

three. CoreData Specific Use

The final goal is to obtain the context Nsmanagedobjectcontext, through which to implement additions and deletions, the actual development of the data will remember to put these functions in different functions.

Use CoreData func usecoredata () {///store data in the sandbox's document//Get the context for managing data (choosing use Core data when creating a project makes it easier to implement the following code, if not There is a choice, must code implementation Configuration "self-Baidu") Let app = Uiapplication.sharedapplication (). Delegate as! Appdelegate Let context = app.managedobjectcontext//* Insert create Object from entity var user = Nsentitydescription.in Sertnewobjectforentityforname ("Users", Inmanagedobjectcontext:context) as! users//Why do you want to add as!? Users?        Because it will return the Mamageobject//operand user.id=1 user.name = "Jom" user.age = 21//* Save data (insert completed)        Do {try Context.save ()}catch is nserror{print ("Storage Failed")}//* Query operation var fetchrequest = nsfetchrequest (entityname: "Users")//Declares entity request (note entity name is capitalized) "Fetch: Get"//Set query condition Fetchrequest . predicate = nspredicate (format: "id = ' 1 ' and name= ' Jom '")//multi-condition lookup, also fuzzy lookup let result = try! Context.executefetchrequest (fetchrequest) as! [The users]//return value is an array, and if no query is reached, an empty//let is returned FetchedemployeEs = Try Context.executefetchrequest (fetchrequest) as! [users]//return value is an array this is all query do{let result = Try Context.executefetchrequest (fetchrequest) as! [Users] Print ("Quantity is", result.count)///"important" depending on whether this decision is found, only modify or delete, do not let empty array manipulation error}catch is nserror{p Rint ("No Search to")} defer{Print ("Query result:")}//* modify (on the basis of the query, modify the object to be queried, and then save it) if result.count==0 {        Print ("No query value, cannot be modified")}//originally for Tom//out of fault, because there is no search, directly to an empty array assignment, resulting in the program termination, after the establishment of this situation is determined whether the empty first.            else{print ("can modify") result[0].id=2} do{try Context.save ()//The exception should be caught in practice}catch{ Print ("Modify Failed")}//delete data (also on the basis of finding, delete, save once) if result.count==0 {print ("No query value, cannot modify")}//originally T        OM//out of fault, because there is no search, directly to an empty array assignment, causing the program to terminate, after the establishment of this condition to determine whether it is empty first. else{print ("can delete") Context.deleteobject (Result[0])} try! Context.save ()}

Iv. Use of Nsfetchedresultscontroller

In the development process, you may use CoreData in the table (table) , Apple designed the controller in order to optimize the memory, provide AH program performance

When used in a controller, it is generally followed by its Nsfetchedresultsdelegate protocol, importing import CoreData, and importing entities to create nsfetchedresultscontroller (similar to a method).

For more information, please refer to: http://www.starming.com/index.php?v=index&view=30

Official documents; Nsfetchedresultscontroller Class Reference

Nsfetchedresultscontrollerdelegate Protect Reference

Official documents: CoreData Programming Guide

Introduction to Core Data Reference Collection < focus >




iOS Development Learning notes-data persistence core

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.