How do I retrieve managed objects whose dates fall within one week of a given date?

Discussion in 'iOS Programming' started by moonman239, Jan 14, 2014.

  1. moonman239 macrumors 68000

    Mar 27, 2009
    Example scenario: I have multiple employees in a database. This database has information on when each employee joined a given department. The end user wants to know how many people have joined the department in the past 7 days.

    I wouldn't want the app to fetch all of the employee records, then comb through every record looking for records of employees who joined in the past 7 days.
  2. waterskier2007 macrumors 68000


    Jun 19, 2007
    Novi, MI
    What kind of database (basic SQLite, Core Data, etc)? Is it local on the iOS device?
  3. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    SQLite. I found an answer online, thanks to Google and to a helpful person at StackOverflow.

        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDate *startOfWeek;
        NSTimeInterval timeInterval;
        [calendar rangeOfUnit:NSWeekCalendarUnit startDate:&startOfWeek interval:&timeInterval forDate:[NSDate date]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >=%@)",startOfWeek];
    // Execute a fetch request with [I]predicate[/I] set as a predicate.
  4. moonman239, Jan 14, 2014
    Last edited: Jan 16, 2014

    moonman239 thread starter macrumors 68000

    Mar 27, 2009
    [__NSCFNumber timeIntervalSinceReferenceDate]: unrecognized selector sent to instance

    I can't figure out why my code would give me this error. Below are the relevant lines of code.

    NSDate *date = [NSDate date];
    double timestamp = [date timeIntervalSince1970];
    EDIT: After reading this Webpage, I found that the problem lies in the code for the predicate I created so that the app would fetch the managed object that corresponds to the given date. Instead of telling it to compare an NSDate object to date, I compared it to timestamp.
  5. ArtOfWarfare macrumors G3


    Nov 26, 2007
    What? There's no predicate in the two lines of code you showed us...
  6. moonman239 thread starter macrumors 68000

    Mar 27, 2009
    Core Data model seems to have no managed objects that meet date predicate.

    My app has a database. In the database's entity is a date attribute. In one of my view controllers, the app is supposed to fetch managed objects whose dates fall on the same week as the current date. I have determined that the predicate is the only problem. Its code is below this paragraph.

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >=%@)",startOfWeek];
    EDIT: startOfWeek is an NSDate object that is set to the correct value.

Share This Page