iOS Realm按日期分组到tableView部分

时间:2015-09-27 12:48:46

标签: ios objective-c realm

我有realm数据库,其中包含添加此数据的数据和日期。我想提取这个并将日期设置为表视图部分标题和数据,因为每个部分的行数据取决于日期。我知道如何exctract但不知道如何按日期分组,并根据日期设置每个部分的数据。谢谢!

4 个答案:

答案 0 :(得分:5)

使用高阶函数的Swift 4 实现,而不是循环。

class Item: Object {
  @objc dynamic var id: Int = 0
  @objc dynamic var date: Date = Date()
}

let realm = try! Realm()

// fetch all Items sorted by date
let results = realm.objects(Item.self).sorted(byKeyPath: "date", ascending: false)              

let sections = results
    .map { item in
        // get start of a day
        return Calendar.current.startOfDay(for: item.date)
    }
    .reduce([]) { dates, date in
        // unique sorted array of dates
        return dates.last == date ? dates : dates + [date]
    }
    .compactMap { startDate -> (date: Date, items: Results<Item>) in
        // create the end of current day
        let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!
        // filter sorted results by a predicate matching current day
        let items = results.filter("(date >= %@) AND (date < %@)", startDate, endDate)
        // return a section only if current day is non-empty
        return items.isEmpty ? nil : (date: startDate, items: items)
    }

答案 1 :(得分:3)

您可以按日期对检索到的<?php require_once 'db.con.php'; $stmt = $pdo->prepare("SELECT 1 FROM users WHERE id=?"); $stmt->execute(array($_GET['userID'])); $row = $stmt->fetch(); if(!$row) { header("Location: logout.php"); exit; } $id = $row['id']; $name = $row['name']; echo "My id is $id and my name is $name"; 进行排序,然后在迭代时将其拆分,以便以分组/层次结构方式对其进行访问。

 send_data(g.to_blob, :disposition => 'inline',  :type => 'image/png',  :filename => "chart.png

注意:这样,您需要将所有元素保留在内存中。如果这不适合您,根据您的使用情况,您可以只记住索引,您可以使用它来从检索到的Results访问该元素。

答案 2 :(得分:2)

我有完全相同的问题,我需要在分段表中显示一种Realm实体,按日期分组,这就是我的做法。

包含日期字段的示例类:

final class Appointment: Object {
    @objc dynamic var id: Int = 0
    @objc dynamic var date: Date?
}

将获取所有对象并将其拆分为部分/结果的示例代码,按唯一日期分组:

// (un)safely get an instance of Realm
let realm = try! Realm()

// get all the dates
// note that begginingOfDay is a extension on Date
// which gives back the beggining of the day of the given Date as a Date
// we are doing this in order to filter out non-unique dates later
let dates = self.realm.objects(Appointment.self).toArray().flatMap({ $0.date ?? nil }).map({ $0.beginningOfDay() })

// cast it to a Set to make values unique, and back to an Array for further use
let uniqueDates = Array(Set(dates))

let predicates = uniqueDates.map({ date -> NSPredicate in

    // in order to use Swift's Date with NSPredicate
    // it must be casted to NSDate
    let begginingOfDay = date.beginningOfDay() as NSDate
    let endOfDay = date.endOfDay() as NSDate

    // create a predicate that checks if the given Date is in between
    // the beggining of a given Date and the end of the given Date
    let predicate = NSPredicate(format: "(date >= %@) AND (date <= %@)", begginingOfDay, endOfDay)

    return predicate
})

// create an array of Results<Appointment>, and then use it to drive your table/collection view
// I will leave this part to you, depends on your UI implementation
// personally, I wrap this into another object that contains results, section index, section title, etc.
// and then I use all of that in my table view's data source methods          
let sectionedResults: [Results<Appointment>] = predicates.map({ predicate -> Results<Appointment> in
    let results = realm.objects(Appointment.self).filter(predicate)
    return results
})

您现在应该大致了解如何知道,我将把UI实现的细节留给您。

答案 3 :(得分:0)

如果有人在使用Swift 3.0语法:

    var lastDate = dateObjects.first?.start
    let calendar = Calendar.current
    var lastGroup = [DateObject]()
    var days = [[DateObject]]()

    for dateObject in dateObjects {
        let currentDate = dateObject.start
        let unitFlags : Set<Calendar.Component> = [.era, .day, .month, .year, .timeZone]
        let difference = calendar.dateComponents(unitFlags, from: lastDate!, to: currentDate)

        if difference.year! > 0 || difference.month! > 0 || difference.day! > 0 {
            lastDate = currentDate
            days.append(lastGroup)
            lastGroup = [travelTime]
        } else {
            lastGroup.append(dateObject)
        }
    }
    days.append(lastGroup)