Created
February 24, 2016 13:10
-
-
Save sigwyg/ab520157c49ee2591c6f to your computer and use it in GitHub Desktop.
Swift でCoreDataを利用してデータを永続保存するサンプル。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// prepare | |
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate | |
let context: NSManagedObjectContext = appDel.managedObjectContext | |
// save data | |
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) | |
newUser.setValue("sigwyg", forKey: "username") | |
newUser.setValue("pass123", forKey: "password") | |
// contextにアクセスするには、エラー処理が必要 | |
do { try context.save() } catch { print("Cause Error") } | |
// fetch data | |
let request = NSFetchRequest(entityName: "Users") | |
// 検索に失敗した際にもオブジェクトを返すかどうか | |
request.returnsObjectsAsFaults = false | |
// エンティティを検索するときに条件を付ける | |
request.predicate = NSPredicate(format: "username = %@", "sigwyg") | |
do { | |
let results = try context.executeFetchRequest(request) | |
if results.count > 0 { | |
for result in results as! [NSManagedObject] { | |
print(result.valueForKey("username")!) // Optionalになっているので、!でアンラップする | |
print(result.valueForKey("password")!) | |
// valueForKeyの結果はAnyObjectを返すので、混乱を避けるためStringにダウンキャストする | |
if let username: String = result.valueForKey("username") as? String { | |
print(username) | |
context.deleteObject(result as! NSManagedObject) | |
do { try context.save() } catch { print("delete failed") } | |
} | |
} | |
} | |
} | |
catch { print("Fetch Failed!") } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment