【发布时间】:2014-11-02 22:10:35
【问题描述】:
问题
我是 IOS 开发的新手,一直在努力使用 Core Data。我正在尝试使用开关创建设置页面。我需要记住这个开关是打开还是关闭。我创建了一个核心数据应用程序,并设法弄清楚如何将开关的值保存到属性中。下面的代码做到了这一点,我只是不知道如何将开关的保存值恢复为打开或关闭。我该怎么做?谢谢!
核心数据图片
代码:
import UIKit
import CoreData
class preferencesStuff: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Settings")
request.returnsObjectsAsFaults = false;
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0){
if results[results.count-1] as NSObject == 1 {
println("ON")
}
}else{
println("NO RESULTS")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var fractSwitchValue: UISwitch!
@IBAction func fractSwitch(sender: AnyObject) {
if fractSwitchValue.on == true {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newSetting = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as NSManagedObject
newSetting.setValue(true, forKey: "fractionOnOff")
context.save(nil)
//println(newSetting)
}
else {
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newSetting = NSEntityDescription.insertNewObjectForEntityForName("Settings", inManagedObjectContext: context) as NSManagedObject
newSetting.setValue(false, forKey: "fractionOnOff")
context.save(nil)
//println(newSetting)
}
}
}
【问题讨论】: