2

I am creating and using time base UUID for items. I am using this function:

  class func timeBasedUUID() -> NSUUID {
    let uuidSize = sizeof(uuid_t)
    let uuidPointer = UnsafeMutablePointer<UInt8>.alloc(uuidSize)
    uuid_generate_time(uuidPointer)
    let uuid = NSUUID(UUIDBytes: uuidPointer)
    uuidPointer.dealloc(uuidSize)
    return uuid
  }

And now I would like to know how can I sort them from oldest to newest. I was thinking about comparing strings but it is correct? Because I don't think so.

Libor Zapletal
  • 13,752
  • 20
  • 95
  • 182

2 Answers2

3

UUIDs have no "oldest" or "newest" component. It's true that uuid_generate_time uses the time to help guarantee uniqueness, but it is not intended as a way of actually recording the time. Don't try to misuse it in this way. If you know you're going to need to sort items by date, you need to give them an additional bit of information, e.g. a timestamp.

matt
  • 515,959
  • 87
  • 875
  • 1,141
1

Decoding timestamp from UUIDv1 in swift:

extension UUID {
    static func timeBasedUUID() -> UUID? {
        let uuidSize = MemoryLayout<uuid_t>.size
        let uuidPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: uuidSize)
        uuid_generate_time(uuidPointer)
        let uuid = uuidPointer.withMemoryRebound(to: uuid_t.self, capacity: 1) {
            return $0.pointee
        }

        uuidPointer.deallocate()
        return UUID(uuid: uuid)
    }

    var timestamp: TimeInterval {
        let components = uuidString.split(separator: "-")
        assert(components.count == 5)
        let hex = String(components[2].dropFirst()) + components[1] + components[0]
        // 100-nanoseconds intervals
        let interval = Int(hex, radix: 16)!
        let seconds = TimeInterval(interval / 10000000)

        // -12219292800 relative seconds to 1970
        return seconds - 12219292800
    }
}

references:

Kirow
  • 1,077
  • 12
  • 25