標籤:coredata data model swift ios
上一話我們定義了與coredata有關的變數和方法,做足了準備工作,這一話我們來試試能不能成功。首先開啟上一話中產生的Info類,在其中引用標頭檔的地方添加一個@objc(Info),不然後面會報錯,我也不知道為什麼。
然後在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 //相當於取到了Info,可以進行賦值操作 tempInfo.name = "cg" tempInfo.location = "xidian" //記得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.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 println("name: \(temp.name), localtion: \(temp.location)") } } } } }} 以上代碼的作用是通過代理的方式,先向Info中插入一個執行個體的值,name屬性為cg,location屬性為xidian,然後再進行查詢,把列印出來,運行後中控台顯示如下:
有了插入和查詢,下面實現更新操作,在上面的代碼中增加如下代碼:
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) } }
以上代碼的作用是把name為cg的執行個體的name改成cggggg,運行結果如下:
現在來實現刪除的操作,與update的操作類似,在update代碼的基礎上把修改名字的代碼改成:
managementContext.deleteObject(temp)
就好了,現在我們試著刪除名為cggggg的記錄,可以看到cggggg已經不在了,在這就不了大家自己試試。
swift語言IOS8開發戰記22 Core Data3