Read a foreign article, about iOS9 core data teaching, here to do a summary of core data teaching
Example Open Source Address: lastdaycoredata
In this article we will learn a series of core data tutorials that you will use Swift2.0 to write your core data. You will find in Xcode that it is very easy to get started from the boot code tutor data Model Editor. At the end of the tutorial, you will learn:
- Use Xcode's Model editor to store what you want in core Data.
- Add a new record to Core Data
- Reading a set of data from core data
- Show the results obtained in the table view
You'll also learn what the data behind core database is and how to interact with it. OK, now let's build my app.
Begin
Open your Xcode to create a new iphone project, select the single View application template named Hitlist and select Use Core Data.
The core Data stack sample code is generated in Appdelegate.swift when the Use Core data check box is selected
The core data stack consists of a set of objects that facilitate the retrieval and preservation of core data. There is one object that is the most holistic to manage the state and data model of care data, and so on.
The idea of this sample program is simple. There is a table view called "Hit list". You can add a name to this list, and eventually you will use core data to make sure that the data is between the various links.
Click Main.storyboard in interface Builder. Next click on Editor and select navigation Controller. Specific operation:
Return to Interface Builder and drag a table view.
Next drag a bar Button item to place it on the navigation bar. Finally, it is named Add. Just like this.
Each time you click Add, a pop-up box containing the text information field appears on the screen. Where you can enter the default name into the text field.
If you want to know why, you can not set a delegate that represents the diagram so that no behavior is triggered.
Open Assistant Editor Drag table view to Viewcontroller.swift and insert a outlet in the class:
Named TableView.
@IBOutlet weak var tableView: UITableView!
Also drag add to Viewcontroller.swift and create an action named AddName:
@IBAction func addName(sender: AnyObject) { }
Now you can refer to the representation diagram and buttons. The next step is to create a representation diagram model. Add the code in Viewcontrroller.swift:
//Insert below the tableView IBOutletvar names = [String]()
Names is an array of variable shtring types, which is displayed in TableView.
Implement the Code in Viewdidload ():
override func viewDidLoad() { super.viewDidLoad() title = "\"The List\"" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")}
Here you will create a title that registers UITableViewCell in the table view class. Table View will return the correct type of cell
Still in Viewcontroller.swift, add uitableviewdatasource,uitableviewdelegate
//Add UITableViewDataSource to class declarationclass ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{ //这里添加tableView.dataSource = selftableView.delegate = self}
This time Xcode will prompt Viewcotroller to not meet the protocol. Implement the data source method to modify this error.
// MARK: UITableViewDataSourcefunc tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count} func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell!.textLabel!.text = names[indexPath.row] return cell!}
If you have used UITableView, this code will look very similar. The first method is the number of names.
The second method, TableView (_:cellforrowatindexpath:), returns to the Cell object.
Don't run it now. First you need a way to input names and then display them in table view.
Implement AddName Ibaction
//Implement the addName IBAction@IBAction func addName(sender: AnyObject) { let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in let textField = alert.textFields!.first self.names.append(textField!.text!) self.viewWillAppear(true) self.tableView.reloadData() }) let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil)}
Each time you click the Add button, this method pops up the text field and two buttons to save and cancel.
Click Save to insert its name into the array, and the table view will reload the data and display it.
Here, build and run our application for the first time. Clicking on the Add button at the top will insert a bullet box.
Add 4 or 5 or so of data, just like the following
Your table view will show the data, but it can't be persisted, what does it mean? This means that our current array data is stored in memory, but if we force the application to quit or reboot your device, your array data will be destroyed.
Core data provides persistence, meaning that he can keep the data persistent, even if the app restarts or runs again.
You are not adding any core Data yet. Let's test, switch to simulator, click Shift+?+h, and it will return to the home screen.
See the Hitlist icon, click on it to switch to the app, these names exist as well. This is not the same as what we have just described, why?
When you click on the Home button. This time the operating system freezes all the information currently in memory for an instant. Include our name array string. Similarly, when our app switches back, the OS will restore the memory of the past, just as you've never left it, meaning our names has been restored.
Multi-tasking mode is available in iOS 4 earlier. Do they create a seamless experience for iOS users and also add a concept of continuity that really exists?
No, it's not true. If you kill the app completely or close your iphone, your names array will disappear. You can experience the next, quick double-click home.
Here, pull up your application, and you'll kill the program here. This time back home, once again click on your application, names will disappear.
There are differences between the two methods shown above, so it seems obvious that familiarity with multi-tasking mode is a good idea. But this is no different in the user's mind. Users don't care which way to cut back to home, or cut back to the app.
The question now is how to get the app to return in any way that can exist.
Now it's time for us to tell the truth, and to achieve true persistence, the data will exist in an application, no matter what.
Data modeling
Now that you know how to detect persistence, let's start with core data learning. Your goal is simply to persist the name you entered and still exist in the application after restarting.
Here, you've learned how to store names names in memory. Here you will use core data instead of that method.
The first step is to create a managed object model that means that the core data will be on disk. By default, Core data uses the SQLite database as a persisted storage, so you can imagine the data model as a database schema.
When you created the project, we chose use Core Data,xcode to automatically create a data model file called Hitlist.xcdatamodeld.
Click Hitlist.xcdatamodeld to open it, as you can see, Xcode has its own data Model Editor, just like that
This data model has many functions, so let's create a simple data entity.
At the bottom left, click Add entity to create a new entity, double-click our newly created entity, and rename it to person, like this:
You may be wondering why the Data Model Editor uses "entities" rather than simply defining a new class. You'll soon see that Core data comes from its own vocabulary. Here are some common book words you might encounter:
- In core data, an entity is the definition of a class. A typical example is an example of an employee and a company. In a relational database, an entity corresponds to a table.
- A attribute is part of the information that is connected to a specific entity. For example, an employee can have a name, position, salary, etc. attribute. The attribute (attribute) in the database corresponds to a specific field in the table.
- Relationship is a connection between multiple entities.
Now that you know what attribute is, return to the Model Editor and add a attribute to person, select person, click +.
Create a name and select the type string.
String is one of the many data types that are contained in core database.
Save data to Core
Import Core Data in Viewcortroller.swift
//Add below "import UIKit"import CoreData
In objective-c you may have to manually link the framework, but in Swift, a simple import statement allows you to use the API in your code.
Next, replace the model.
//将names变味people,并且将people类型改为NSManagedObject类型var people = [NSManagedObject]()
Next you store the person entity instead of names, so rename the data model to people, and it is now the Nsmanagedobject type instead of the simple string type.
Nsmanagedobject is known as a single object in core data. You have to use it to create, modify, save and delete operations on your persistent data.
Just as you have changed the model of the view, you must also replace the original data source with the following code.
//Replace both UITableViewDataSource methodsfunc tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count} func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") let person = people[indexPath.row] cell!.textLabel!.text = person.valueForKey("name") as? String return cell!}
In fact, by comparing the most significant changes in the Cellforrowatindexpath, a closer look will be able to find the changes therein.
Of course, the point you need to be aware of is how you grabbed the name attribute from Nsmanagedobject.
cell!.textLabel!.text = person.valueForKey("name") as? String
Why use the above method? Because Nsmanagedobject does not know how name is defined in your data model in your data model, there is no way to access your Name property directly. The only way to do this is to use the Key-value provided by core data to read it, which is often called KVC.
I am also here to briefly introduce the KVC bar. That is, if you are a new iOS developer you may not know what is KVC or Key-vale encoding. KVC is the mechanism of cocoa and cocoa touch to access an object while the property indirectly uses a string to identify it. In the above case, KVC is like a dictionary.
The next step is to change our @ibaction AddName method:
let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in let textField = alert.textFields!.first self.saveName(textField!.text!) self.tableView.reloadData()})
See above we have a new Savename method added
func saveName(name: String) { //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext:managedContext) let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) //3 person.setValue(name, forKey: "name") //4 do { try managedContext.save() //5 people.append(person) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") }}
What's all this? Let's analyze it.
- Before you do the svae operation, you need to get nsmanagedobjectcontext first. You can think of this as being used to managed object context. To save the object to core data takes two steps, first, you need to insert an object into the managed object context. The object is then committed and stored to disk. Xcode has actually produced a generic template when you choose to use Core data. This default managed object context exists in the application delegate. To refer to it, you need to get an app delegate reference.
- Create the managed object context and complete the initialization of the Nsmanagedobject, init (entity:insertintomanagedobjectcontext:). You might think about all the nsentitydescription.
- With Nsmanagedobject, you must use the name you created, you must use KVC, or you will get a crash.
- Your commit person is saved on disk, note that save throws an exception, which is why we need to use try do.
- The next step is to congratulate you on your successful and safe implementation of data persistence. Still the view will reload when we insert
This can be a lot more complicated than using a string, but it's not very complicated. The code here is to get managed object context and entity,
Build and run and add some names like the following.
If your data is already stored in core data and it is persisted, this time we kill our app, then reload our program, wait a minute, what happened? Table View is empty
You survive to core data but not after reloading and still empty, actually the data is actually waiting there, and you don't show it,
Get from Core data
To get persisted data, you have to take it out. Add a method to Viewcontroller.swift Zhongtian
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let fetchRequest = NSFetchRequest(entityName: "Person") //3 do { let results = try managedContext.executeFetchRequest(fetchRequest) people = results as! [NSManagedObject] } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") }}
What has been done in the above code?
- As you just said, you need to get a managed object context before doing some operations. References managed object context from delegate.
- As you can see by name, Nsfetchrequest is the data returned.
- Executefetchrequest () returns the standard array specified in the read request that satisfies the managed objects.
Build and rerun, and you'll find the results you want.
Now you can test it at random.
Core Data Teaching