CoreData 자세히 보기
동작 이미지
CoreData란
객체를 지속하는 프레임워크를 위해 객체와 관계 데이터베이스 SQLite 간에 처리할 수 있습니다."O/R 매핑"을 어디서 들은 적이 있습니까? 바로 CoreData입니다.
CoreData 사용 준비
솔리드 작성
CoreData의 모델 편집기에서 ToDo 솔리드를 만들고 Attributes에서 String으로 "memo"를 추가합니다.
화면 만들기
ViewController 수정 사항
ViewController.swift
import UIKit
import CoreData
class ViewController: UIViewController {
var obj : NSManagedObject? = nil
@IBOutlet weak var tfMemoCreate: UITextField!
@IBOutlet weak var tfMemoRead: UITextField!
@IBOutlet weak var tfMemoUpdate: UITextField!
// Save
@IBAction func btnSaveAction() {
if(tfMemoCreate.text == "") {
return
}
// Get ManagedObjectContext
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
// Create new ManagedObject
var newTodo = NSEntityDescription.insertNewObjectForEntityForName("ToDo", inManagedObjectContext: managedContext) as NSManagedObject
newTodo.setValue(tfMemoCreate.text, forKey: "memo")
// Error handling
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error)")
}
println(newTodo)
println("Object Saved")
}
// Read
@IBAction func btnLoadAction() {
if(tfMemoRead.text == "") {
return
}
// Get ManagedObjectContext
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
// Set search conditions
let fetchRequest = NSFetchRequest(entityName: "ToDo")
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = NSPredicate(format: "memo = %@", tfMemoRead.text)
var error: NSError?
// Get result array from ManagedObjectContext
var fetchResults: Array = managedContext.executeFetchRequest(fetchRequest, error: &error)!
if(fetchResults.count > 0){
obj = fetchResults[0] as? NSManagedObject
let memo: String = obj!.valueForKey("memo") as String
tfMemoUpdate.text = memo
println(obj)
println("Object Read")
}else {
println("Could not fetch \(error)")
tfMemoUpdate.text = "Error: Memo Nothing."
}
}
// Update
@IBAction func btnUpdateAction() {
// Get ManagedObjectContext
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
// Change value of managedObject
if(obj != nil){
obj?.setValue(tfMemoUpdate.text, forKey: "memo")
// Save value to managedObjectContext
var error: NSError?
if !managedContext.save(&error) {
println("Could not update \(error)")
}
tfMemoUpdate.text = obj?.valueForKey("memo") as String
println(obj)
println("Object updated")
}
}
// Delete
@IBAction func btnDeleteAction() {
// Get ManagedObjectContext
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
// Delete managedObject from managed context
if(obj != nil){
println(obj)
managedContext.deleteObject(obj!)
// Save value to managed context
var error: NSError?
if !managedContext.save(&error) {
println("Could not update \(error)")
}
obj = nil
println("Object Deleted")
tfMemoUpdate.text = ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
참고 자료
Swift를 통한 CoreData 구현
Swift 학습 – CoreData CRUD 운영 샘플
Reference
이 문제에 관하여(CoreData 자세히 보기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/moco3/items/650111d8bc39ccd0c3c9텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)