简体   繁体   中英

How to keep track of data over various periods of time (Swift) - Counter/Habit Tracking App

I'm trying to create a simple counter/habit tracking app that allows users to see how many times they've completed a task over a certain amount of time (daily/weekly/monthly/yearly/total).

My question is: what is the best way to track variables over time such that when the user selects a time period, the variable's value can update to reflect that change?

A few examples to clarify what I mean:

  • A user who initially created a monthly timer to track workouts should be able to switch to a weekly timer and see the data update as needed (there should be fewer in a week than in a month).
  • A user who has created a daily counter should see the daily counter reset to 0 at midnight each day, with the previous day's value visible to compare.
  • A user who has created a "total" counter should be able to switch to any time period (daily/weekly/monthly/yearly) and see the counter update as needed.

The UI for my app is basically a custom tableview with the counter number, counter name, and the time period over which the counter number is being tracked. A detail view allows users to add to/subtract from the counter's value.

I have been wracking my brain and Google for a long time, so I'd really appreciate any help!

Each task should have a date. When app needs to query for the average per day/week/month/year you can use a NSPredicate to restrict only the results from a given time period.

For instance, here's a predicate that models the last-week scenario that I have written for an app of mine:

  func lastWeekPredicate() -> NSPredicate {
    let calendar = NSCalendar.currentCalendar()
    let endDate = NSDate()
    let startDate = calendar.dateByAddingUnit(.CalendarUnitDay, value: -7, toDate: endDate, options: nil)
    return NSPredicate(format: "day >= %@ AND day =< %@", argumentArray: [startDate!, endDate!])
  }

Let's say you modelled your data with Core Data. Querying with this predicate would give you the results of all the tasks that were completed in the last week. The predicate can be modified to work for days, months, year, or any specified number of days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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