Swift language IOS8 development war 22 Core Data3, swiftios8
In the previous section, we defined variables and methods related to coredata, and made full preparations. Let's try to see if they can succeed. First, open the Info class generated in the previous step and add @ objc (Info) to the place where the header file is referenced. Otherwise, an error will be reported and I do not know why.
Then add the following code to viewController:
Import UIKitimport CoreDataclass ViewController: UIViewController {var tempInfo: Info! Override func viewDidLoad () {super. viewDidLoad () if let managementContext = (UIApplication. sharedApplication (). delegate as AppDelegate ). managedObjectContext {tempInfo = NSEntityDescription. insertNewObjectForEntityForName ("Info", inManagedObjectContext: managementContext) as Info // It is equivalent to obtaining Info. You can assign values to tempInfo. name = "cg" tempInfo. location = "xidian" // remember save var e: NSError? If managementContext. save (& e )! = True {println ("insert error \ (e !. LocalizedDescription) ")} if let managementContext = (UIApplication. sharedApplication (). delegate as AppDelegate ). managedObjectContext {var fetchRequest = NSFetchRequest (entityName: "Info") var result = managementContext.exe cuteFetchRequest (fetchRequest, error: & e) as [Info] if e! = Nil {println ("fetch result error: \ (e !. LocalizedDescription) ")} else {for item: AnyObject in result {let temp = item as Info println (" name: \ (temp. name), localtion: \ (temp. location )")}}}}}}
The above code is used as a proxy to insert an Instance value to Info, the name attribute is cg, And the location attribute is xidian, then query and print it out, after running, the console is displayed as follows:
With insert and query, the following update operations are implemented. The following code is added in the above Code:
if let managementContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext { var fetchRequest = NSFetchRequest(entityName: "Info") fetchRequest.predicate = NSPredicate(format: "name = 'cg'", argumentArray: nil) var result = managementContext.executeFetchRequest(fetchRequest, error: &e) as [Info] if e != nil { println("fetch result error: \(e!.localizedDescription)") } else { for item: AnyObject in result { let temp = item as Info temp.name = "cggggg" println("name: \(temp.name), localtion: \(temp.location)") } managementContext.save(&e) } }
The above code is used to change the name of the instance whose name is cg to cggggg. The running result is as follows:
Now, the delete operation is similar to the update operation. On the basis of the update code, change the code for modifying the name:
managementContext.deleteObject(temp)
Now, let's try to delete the record named cggggg. We can see that cggggg is no longer there, so we can't try it on our own.