One of Core data use (Swift): Save

Source: Internet
Author: User
Tags sqlite database

Core data is used to persist data, which is a technology based on the SQLite database.

So how is it implemented in Swift?

First, you need to create a new template, open the project in the Xcdatamodeld file, click "Add Entity", this time, the creation of a template. After that, you can modify the name of the template to the name you want. Then, in attributes, click "+", add the field and modify the type.

Then, in the code "import CoreData". Next, save the object with Nsmanagedobject, which can be converted to any object. Its type is a dictionary.

To read data from an existing list:

var fileslist = [Nsmanagedobject] ()

String name = Filelist[0].valueforkey ("name") as String?

Save the sample, divided into five steps:

Save data to Entity

Func savefiles (name:string, content:string) {

The first step is to get the core data agent:

Let appdelegate = Uiapplication.sharedapplication (). Delegate as Appdelegate//General Agent

Step two, get the managedobject.

Let Managedcontext = Appdelegate.managedobjectcontext

The third step is to get the entity:

Let entity = Nsentitydescription.entityforname ("article", inmanagedobjectcontext:managedcontext!)

The fourth step is to initialize the object to be inserted and set the value of the object:

Let file = Nsmanagedobject (entity:entity!, Insertintomanagedobjectcontext:managedcontext)

File.setvalue (name, Forkey: "Name")

File.setvalue (Content, Forkey: "Content")

Fifth Step, Save:

var error:nserror? = Nil

managedcontext!. Save (&error)

Sixth step, save the data to the list

Self.filesTable.insert (file, atindex:0)

}

One of Core data use (Swift): Save

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.