Using Core Data in Swift (i)

Source: Internet
Author: User



CoreData is the standard data storage method in Mac and iphone applications. Therefore, it is necessary for us to learn this technique. So what are we going to create? The first is a table view to process the data, add, delete, edit, and find and sort. The data will be saved all the time, even if the device is restarted. Because, this data is placed in SQLite.



Apple's official description of core data, "theCore data library is a high-level automatic management object life cycle and durable solution."



Next, we'll start with a step-by-step. Start by creating a Xcode6 project, select Single-view-template, select Swift in the language, select Open Core Data. This project is called MyLog.






Open the Appdelegate.swift and you will find that a lot of code has been generated. These are the initialization and setting of core data. Using Core Data, the first thing you need to know is managedobjectcontext, and here's the definition:

lazy var managedObjectContext: NSManagedObjectContext? = {
    // Returns the managed object context for the application (which is already bound to the persistent store
    // coordinator for the application.) This property is optional since there are legitimate error
    // conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext ()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
} ()

"After the project is created, Xcode will automatically add the CoreData library. The NSManagedObjectContext, NSManagedObjectModel, NSPersistentCoordinator properties and saveContext, applicationDocumentDirectory are automatically added to the AppDelegate. Of course, the most important thing is to create the xcdatamodeld file. If you do n’t start the project When you choose to use CoreData, you can add these contents manually. This way you can use Core Data.

For the most part, all you really need to know about this though, is that managedObjectContext is a lazily computed variable on AppDelegate. Knowing this we can find it from our ViewController.swift file. For example in viewDidLoad () of ViewController.swift, we can use this code to print the managedObjectContext's description to the console.

First we need to set up a lazily loaded variable in the ViewController.swift file that can help us get the managedObjectContext from the app delegate using the UIApplication.sharedApplication (). Delegate property. Note that you'll need to import CoreData in order to use the NSManagedObjectContext class name here.

import UIKit
import CoreData

class ViewController: UIViewController {

    lazy var managedObjectContext: NSManagedObjectContext? = {
        let appDelegate = UIApplication.sharedApplication (). delegate as AppDelegate
        if let managedObjectContext = appDelegate.managedObjectContext {
            return managedObjectContext
        }
        else {
            return nil
        }
    } ()
    
    override func viewDidLoad () {
        super.viewDidLoad ()
        println (managedObjectContext!)
    }

    override func didReceiveMemoryWarning () {
        super.didReceiveMemoryWarning ()
        // Dispose of any resources that can be recreated.
    }

}
The managedObjectContext variable is computed using the existing managedObjectContext in the application ’s delegate. In viewdidLoad () we cause this variable to be computed by printing it to the console. If your application is set up right you should see something like this:

<NSManagedObjectContext: 0x7fff39c3b790>
You ’ll notice the Xcode template produced an additional file, MyLog.xcdatamodeld.

Opening up this file you can see the Core Data model editor.

Let ’s add a new Core Data entity called LogItem. Our log app will show a list of LogItems, which have a bit of text in them.

Click the "Add Entity" button and select "Data Model Inspector" in the right panel. Here, we can rename the default Entity to LogItem.

Then, click the "+ Attribute" button on the right side below to add the attribute.

Name the first attribute title and set the type to String. Then add an itemText property, the type is also String.

In this way, our first Entity is created. We also need to use this class directly in the code. Xcode provides a tool. Select Editor-> Create NSManagedObject SubClass ... in the menu

Select the MyLog model file in the pop-up box and click Next. Then select the LogItem entity. Select the Swift language in the pop-up file save window. Finally, click the Create button. At this time, you will see a LogItem.swift file has appeared in the project.

import Foundation
import CoreData

class LogItem: NSManagedObject {
    @NSManaged var title: String
    @NSManaged var itemText: String
}
This class is created based on the LogItem in the xcdatamodeld file and represents this entity. The properties of this class represent the attributes of Entity. @NSManaged makes property can operate Core Data Entity.

Finally, a place needs to be modified to use the class created above. In the "Class" field of the Entity menu of the Inspector, prefix the LogItem with the item name, here is: MyLog.LogItem.

In the viewDidLoad method of the ViewController.swift file, initialize several LogItems. There are many ways, but the best way is to use NSEntityDescription's insertNewObjectForEntityForName method.

override func viewDidLoad () {
    super.viewDidLoad ()

    let newItem = NSEntityDescription.insertNewObjectForEntityForName ("LogItem", inManagedObjectContext: self.managedObjectContext!) as LogItem
}
Here, we inserted an object in Core Data using the managedObjectContext generated by the system by default. This method returns an object of type NSManagedObject. This object will respond to the valueForKey method. If you do n’t understand it, it does n’t matter, read on.

In the new object newItem of NSManagedObject, we can use the newItem.valueForKey ("title") method to obtain the title value. But this is not a good way, because you do n’t know when you will misspell the property name, or get the object type wrong.

So, here we convert the type of NSManagedObject to LogItem. This allows direct access to the attribute value. Such as:

 

override func viewDidLoad () {
    super.viewDidLoad ()
    
    let newItem = NSEntityDescription.insertNewObjectForEntityForName ("LogItem", inManagedObjectContext: self.managedObjectContext!) as LogItem
    
    newItem.title = "Wrote Core Data Tutorial"
    newItem.itemText = "Wrote and post a tutorial on the basics of Core Data to blog."
    presentItemInfo ()
}
If we have not claimed the LogItem.swift file before, then the type LogItem is defined. Then you can only use valueForKey to access the property value of the NSManagedObject object. In this way, when calling the Core Data API, you have to use the string comparison method to obtain the type of Entity and state in the running state, which is very troublesome.

Now that we have created a new object, set the title and text properties. We can find this entity. Call the presentItemInfo method at the end of viewDidLoad. This method point definition:

func presentItemInfo () {
    let fetchRequest = NSFetchRequest (entityName: "LogItem")
    if let fetchResults = managedObjectContext! .executeFetchRequest (fetchRequest, error: nil) as? [LogItem] {
        
        let alert = UIAlertView ()
        alert.title = fetchResults [0] .title
         alert.message = fetchResults [0] .itemText
         alert.show ()
     }
}
First, we create an instance of NSFetchRequest and specify to handle entityLogItem. After that, execute the executeFetchRequest method to find the LogItem instance. Because we only set the name of the entity to be searched, the LogItems that are persistent will be found and stored in the instance fetchResults. Finally, the title and message of LogItem are displayed on the screen in UIAlertView.

Run the app and you will see the results on the screen. This is a very simple app.

In the second part, we will discuss handling the content of processing multiple record requests using NSPredicate.

Using Core Data in Swift (1)

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.