Swift Core 数据按天获取结果并排序到带有时间段的表格视图中

Posted

技术标签:

【中文标题】Swift Core 数据按天获取结果并排序到带有时间段的表格视图中【英文标题】:Swift Core data fetch results by day and sort into a tableview with time sections 【发布时间】:2016-03-26 14:25:54 【问题描述】:

您好,我正在尝试加载数据保存到核心数据的特定日期的表。我希望每次保存都是一个部分来加载数据。有许多不同的测量值保存到核心数据中。我不会走得很远。你能帮忙吗?

var totalEntries: Int = 0
var isPerformingSegue = false
var totalDates: Int = 0
var results: NSArray! = NSArray()
var appDel: AppDelegate!
var context: NSManagedObjectContext!
var request : NSFetchRequest!

override func viewDidLoad() 
    super.viewDidLoad()

   appDel = (UIApplication.sharedApplication().delegate as! AppDelegate)
   context = appDel.managedObjectContext
   loadTable()


func loadTable() 
  let today = NSDate()

  // get the current calendar
  let calendar = NSCalendar.currentCalendar()
  // get the start of the day of the selected date
  let startDate = calendar.startOfDayForDate(today)
  // get the start of the day after the selected date
  let endDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startDate, options: NSCalendarOptions())!  

 request.returnsObjectsAsFaults = false
 let dateFormatter = NSDateFormatter()
 dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
 dateFormatter.timeZone = NSTimeZone(name: "GMT") // this line resolved me the issue of getting one day less than the selected date

 totalEntries = context.countForFetchRequest(request, error: nil) as Int!

 request.predicate = NSPredicate(format: "(date >= %@) AND (date <= %@)", startDate, endDate)
 request.sortDescriptors = [NSSortDescriptor(key: "report_id", ascending: false)]

 do 
    var results : NSArray = try context.executeFetchRequest(request)
     catch 
    // Report any error we got. 
    


// MARK: - Table view data source

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
  return results.count
  

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
 let cell: ResultTableViewCell = tableView.dequeueReusableCellWithIdentifier("resultCell") as! ResultTableViewCell

  //get contents and put into cell
  let OurData = results[indexPath.row] as! NSManagedObject

  if indexPath.row == 0 

    let colourLevel: Int = ((OurData.valueForKey("colourLevel"))?.integerValue)!
    cell.resultLabel.textColor = UIColor.whiteColor()
    cell.resultLabel.text = "Colour of Bowel Movement"
    cell.backgroundColor  = GlobalColourConstants.colourColourArray[(colourLevel - 1)]
    return cell

  else if indexPath.row == 1 

    let bmLevel: Int = ((OurData.valueForKey("bMLevel"))?.integerValue)!
    cell.resultLabel.text = GlobalPhrazesConstants.GlobalPhrazesStrings.bMPhrazeArray[bmLevel]
    cell.resultLabel.textColor = UIColor.whiteColor()
    let imageName = GlobalUIImageConstants.bMImageArray[bmLevel]
    let image = UIImage(named: imageName)
    cell.resultIconImageView.image = image
    cell.backgroundColor = GlobalColourConstants.bMColourArray[bmLevel]

    return cell

  else 

    return cell
 

我已经取消了如下方法的日期并且已经更接近了。现在我可以按天数据排序并按时间分段排序。但是我不能显示超过一排(应该不止一排)。

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()

override func viewDidLoad() 
    super.viewDidLoad()

  // core data
  fetchedResultController = getFetchedResultController()
  fetchedResultController.delegate = self
  do 
    try fetchedResultController.performFetch()
   catch _ 
  


  // MARK:- Retrieve Tasks

func getFetchedResultController() -> NSFetchedResultsController 
  fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "savedTimeHourMinute", cacheName: nil)
  return fetchedResultController


func taskFetchRequest() -> NSFetchRequest 
  let fetchRequest = NSFetchRequest(entityName: "UserData")
  let sortDescriptor = NSSortDescriptor(key: "savedTimeMonthDay", ascending: true)
  fetchRequest.sortDescriptors = [sortDescriptor]

  return fetchRequest


func numberOfSectionsInTableView(tableView: UITableView) -> Int 
  if let sections = fetchedResultController.sections 
  return sections.count
 

 return 0


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
  if let sections = fetchedResultController.sections 
    let currentSection = sections[section]
    return currentSection.numberOfObjects
   
  return 0

【问题讨论】:

【参考方案1】:

据我了解,您希望根据创建/保存的日期对条目进行排序,一种方法是向您的实体添加时间戳属性并在保存对象时填充此属性。然后,使用 sortDescriptor 根据时间戳属性对您获取的记录进行排序。大致如下:

let sortDescriptor = NSSortDescriptor(key: "savedTimestamp", ascending: true)
let fetchRequest = NSFetchRequest(entityName: "myRecord")
fetchRequest.sortDescriptors = [sortDescriptor]
//- fetch records as you would
var savedRecords: [myRecord]?
do 
     savedRecords = managedObjectContext.executeFetchRequest(fetchRequest) as? [myRecord]
 catch 
     print("the calamity!")

希望这会有所帮助。

【讨论】:

我已经用新的方向稍微更新了这个问题。我读到 Nsfetchcontroller 是我应该使用的。

以上是关于Swift Core 数据按天获取结果并排序到带有时间段的表格视图中的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift Core Data 中对存储的数据模型提取进行排序

使用 Swift 从 Core Data 中获取数据并在 UITextFields 中显示

Swift Core Data Fetch 按日期和时间存储为字符串并排序

如何使用带有 Swift 的 Core Data 获取非标准(可转换)属性来更新/保存和持久化?

iPhone CoreData:如何按天对获取的结果进行分组?

(Swift) 如何对 Core Data 进行模糊搜索?