简体   繁体   中英

Retrieving Core Data With Swift

Problem

I am new to IOS development, and have been struggling with Core Data. I am trying to create a settings page with a switch. I need to remember if this switch is turned on or off. I created a core data application, and have managed to figure out how to save the value of the switch to the attribute. The code below does this, I just can't figure out how to get the saved value of the switch back as on or off. How would I do this? Thanks!

Picture of Core Data

Coredata

Code:

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)

    }
}

}

I would use NSUserDefaults for this case. It's much easier to use than Core Data when storing user preferences. For example, you would store the property using

NSUserDefaults.standardUserDefaults().setBool(value, forKey: "fractionPreference")

and retrieve it using

let value = NSUserDefaults.standardUserDefaults().boolForKey("fractionPreference")

I just did your example with CoreData. I just happened to store an NSString instead of a Bool. It's not optimized, but it should get you going.

import UIKit
import CoreData

class ViewController: UIViewController {

    var state: NSString = ""

    @IBOutlet weak var fractSwitchValue: UISwitch!

    @IBAction func fractSwitch(sender: AnyObject) {
        if fractSwitchValue.on == true {
            state = "On"
            save(state)
        }
        else {
            state = "Off"
            save(state)
        }
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)

        var appDel = UIApplication.sharedApplication().delegate as AppDelegate
        var context = appDel.managedObjectContext!
        var request = NSFetchRequest(entityName: "Settings")
        var error: NSError?
        var results = context.executeFetchRequest(request, error: &error) as [NSManagedObject]?

        if let fetchedResults = results {
            state = fetchedResults[fetchedResults.count - 1].valueForKey("fractionOnOff") as String!
        } else {
            println("Could not fetch \(error), \(error!.userInfo)")
        }

        if state == "On" {
            fractSwitchValue.setOn(true, animated: true)
        }  else {
            fractSwitchValue.setOn(false, animated: true)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func save(string: NSString) {
        let appDel = UIApplication.sharedApplication().delegate as AppDelegate
        let context = appDel.managedObjectContext!
        let entity =  NSEntityDescription.entityForName("Settings", inManagedObjectContext: context)
        let setting = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)
        setting.setValue(string, forKey: "fractionOnOff")
        println(string)
        var error: NSError?
        if !context.save(&error) {
            println("Could not save \(error), \(error?.userInfo)")
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM