Swift Core数据按天获取结果并排序为带有时间段的tableview

时间:2016-03-26 14:25:55

标签: swift uitableview core-data nspredicate nsfetchedresultscontroller

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

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 个答案:

答案 0 :(得分:0)

根据我的理解,您希望根据创建/保存的日期对条目进行排序,这样做的一种方法是向实体添加时间戳属性,并在保存对象时填充此属性。然后,使用sortDescriptor根据其timestamp属性对您获取的记录进行排序。有点像:

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!")
}

希望这有帮助。