简体   繁体   English

从coredata填充按钮

[英]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. 我有一个具有NSDate属性的实体,该实体可以成功保存。

How on Earth do I fetch the NSDate from the store(year only section) and make it populate the text on a button. 我如何从商店(仅年份部分)中获取NSDate,并使其填充按钮上的文本。 so the button can be pressed later and taken to another View Controller/Table View Controller. 因此可以在以后按下该按钮并将其转到另一个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 使用Swift(希望我已经正确格式化了这个问题,这里有点菜鸟了)谢谢你的期待

//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

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!

You need to execute your fetch request in your context. 您需要在上下文中执行获取请求。

var resultsArray = context.executeFetchRequest(request,nil)
if let arr = resultsArray {
    //we have some results
    var firstObject: FilmInfo = arr[0] as FilmInfo
    var date = firstObject.date
}

If you are interested in only one object you can always set request.fetchLimit = 1 如果您只对一个对象感兴趣,则可以始终设置request.fetchLimit = 1

Getting more advanced you can also fetch only the date property: 要变得更高级,您还可以仅获取date属性:

fetch.propertiesToFetch = ["date"]
fetch.resultType = .DictionaryResultType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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