Skip to content

Instantly share code, notes, and snippets.

@masakid
Created August 3, 2015 11:29
Show Gist options
  • Save masakid/162f05017f2dd65fcfdb to your computer and use it in GitHub Desktop.
Save masakid/162f05017f2dd65fcfdb to your computer and use it in GitHub Desktop.
CoreDataのManagerクラス作ってみた
//
// PersonManager.swift
import UIKit
import CoreData
class PersonManager: NSObject {
//AppDelegateの初期設定
var appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
var managedContext: NSManagedObjectContext?
var entity: NSEntityDescription?
//エンティティー名の設定
var entityName: String = "Person"
//initで起動オブジェクトの設定
override init(){
if let
localManagedContext = appDelegate!.managedObjectContext,
localEntity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: localManagedContext)
{
self.managedContext = localManagedContext
self.entity = localEntity
}
}
//データ追加処理
//引数で追加データを渡して、内部で登録処理実施
func insert(name: String, age: Int){
if let personObject = NSManagedObject(entity: self.entity!, insertIntoManagedObjectContext: managedContext) as? Person {
personObject.name = name
personObject.age = Int16(age)
var error: NSError?
if !managedContext!.save(&error) {
println("保存に失敗...")
}else{
println("保存に成功!")
}
}
}
//データ更新処理
//全件に対して更新処理実施
//対象データのみにする場合、検索、更新処理の実施となる予定(検索は削除の処理を参照)
func updateAddNameAge(){
let fetchRequest = NSFetchRequest(entityName: self.entityName)
var error: NSError?
let fetchResults = managedContext!.executeFetchRequest(fetchRequest, error: &error)
if let results = fetchResults as? [Person] {
for obj in results {
obj.name = obj.name + "*"
obj.age = obj.age + 1
}
if !managedContext!.save(&error) {
println("更新に失敗...")
}else{
println("更新に成功!")
}
}
}
//データ検索処理
//全件データを読み込んで表示
//こちらも削除のNSPredicateを参考にして、検索処理は実装する
func selectAllData(){
let fetchRequest = NSFetchRequest(entityName: self.entityName)
var error: NSError?
let fetchResults = managedContext!.executeFetchRequest(fetchRequest, error: &error)
if let results = fetchResults as? [Person] {
for obj in results {
println("name = \(obj.name), age = \(obj.age)")
}
}
}
//データ削除処理
//検索して削除している。参考にするならここ!
func deleteWhereNameContains(deleteKey : String){
let fetchRequest = NSFetchRequest(entityName: self.entityName)
fetchRequest.predicate = NSPredicate(format: "name contains %@", deleteKey)
var error: NSError?
let fetchResults = managedContext!.executeFetchRequest(fetchRequest, error: &error)
if let results = fetchResults as? [NSManagedObject] {
for obj in results {
managedContext!.deleteObject(obj)
}
}
if !managedContext!.save(&error) {
println("削除に失敗...")
}else{
println("削除に成功!")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment