Search code examples
core-dataswiftnsfetchrequest

populate a button from coredata


I’m spending lots of time trying to figure this out and getting no where.

I have an entity with a NSDate attribute, which successfully saves.

How on Earth do I fetch the NSDate from the store(year only section) and make it populate the text on a button. so the button can be pressed later and taken to another View Controller/Table View Controller.

I have spent hours trying to figure this out, I’m totally stuck can’t find any examples.

Does anyone have the time to help with this please. Using Swift (hopefully I have formated this question correctly, bit of a noob here) Thank you for looking

//year button
@IBAction func btnYear(sender: AnyObject) {

  //APP DEL REFERANCE
  var appdel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
  var context: NSManagedObjectContext = appdel.managedObjectContext!
  let ent = NSEntityDescription.entityForName("FilmInfo", inManagedObjectContext: context)!

  // fetch request
  var request = NSFetchRequest(entityName: "FilmInfo")
  request.returnsObjectsAsFaults = false

Solution

  • First, get the date from your data.

    object.date
    

    Then, format it so you can display it on the button.

    var formatter = NSDateFormatter()
    formatter.dateStyle= .ShortStyle 
    let buttonTitle = formatter.stringFromDate(object.date)
    

    Finally assign the title to the button

    button.setTitle(buttonTitle, forState: .Normal)
    

    To get to the object in the first place, fetch it. Don't forget to execute your fetch request.

    var request = NSFetchRequest(entityName: "FilmInfo")
    request.predicate = NSPredicate(format:"id = %@", aFilmInfoID) // example
    request.fetchLimit = 1
    let results = context.executeFetchRequest(request, error:nil)! as [FilmInfo]
    let object = results.first!