I'm having trouble with an answer I received previously on SOF. That is to say I completely understand the concept as it was explained, but I'm having some trouble with the implementation, I seem to constantly lose the functionality for reading/writing values using the format entity.attribute (Created using functions to save duplicating code).
I'm working on a project using CoreData, an entity called 'Studio' and an attribute called 'name' (String). The functionality is simple, the user sets the value of name and it is saved, if the user presses a refresh key a text label is updated with the current value taken from CoreData.
The issue with my code is that I am inadvertantly creating multiple objects and calling them back at random. The solution I was given was to perform a fetch to see if the object exists and create it if it doesn't.
However as I only wish to work with a single instance of any attributes I create and I will have assigned each an initial value I'm wondering if there is a simple implimentation of this concept somebody can recommend?
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var studioBox: UITextField!
@IBOutlet weak var nameLabel: UILabel!
@IBAction func saveData(sender: AnyObject) {
var studio = writeStudioData()
studio.name = studioBox.text
}
@IBAction func Update(sender: AnyObject) {
var studio = getStudioData()
nameLabel.text = studio.name
}
func getStudioData() -> Studio {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
let request = NSFetchRequest(entityName: "Studio")
request.returnsObjectsAsFaults = false
let result = managedContext.executeFetchRequest(request, error: nil) as [Studio]
return result[0]
}
func writeStudioData () -> Studio {
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
let entityDescription = NSEntityDescription.entityForName("Studio", inManagedObjectContext: managedContext)
let result = Studio(entity: entityDescription!, insertIntoManagedObjectContext: managedContext)
return result
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}