简体   繁体   中英

NSDate without time for condition statement in For loop

Here below is part of my code:

[postQuery findObjectsInBackgroundWithBlock:^(NSArray *myPosts, NSError *error)
 {
     if( !error )
     {
         NSMutableArray *resultArray = [NSMutableArray new];
         NSArray *createdAtGroup = [myPosts valueForKeyPath:@"@distinctUnionOfObjects.createdAt"];

         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         [formatter setDateFormat:@"MM/dd/yyyy"];

         NSCalendar *calendar = [NSCalendar currentCalendar];
         NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit)
                                               fromDate:[NSDate date]];
         NSDate *createdAt = [calendar dateFromComponents:comps];

        for (createdAt in createdAtGroup)
        {
            NSLog(@"createdAt ------> %@", createdAt);

            NSMutableDictionary *entry = [NSMutableDictionary new];
            [entry setObject:[formatter stringFromDate:createdAt] forKey:@"createdAt"];

            NSArray *createdAtSections = [myPosts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"createdAt = %@", createdAt]];
            //NSArray *createdAtSections = [myPosts filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"createdAt = %@", [formatter stringFromDate:createdAt]]];

            for (int i=0; i < createdAtSections.count; i++) {
                NSString *text = [[createdAtSections objectAtIndex:i] objectForKey:@"text"];
                [entry setObject:text forKey:@"text"];

            }
            [resultArray addObject:entry];
        }
         NSLog(@"%@", resultArray);

     }
 }
];

Look at condition statement in For loop:

for (createdAt in createdAtGroup)

I want createdAt declared as NSDate without time so that I can group text into the same date. As I have searched, there seems no way to extract time from NSDate . However, I found this piece of code which they claim to do just that but it doesn't work for me.

 NSCalendar *calendar = [NSCalendar currentCalendar];
         NSDateComponents *comps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit)
                                               fromDate:[NSDate date]];
         NSDate *createdAt = [calendar dateFromComponents:comps];

Is anyone know if I miss anything here or any other way to achieve this? Thanks.

Here I also give my output:

  • 2014-12-08 00:00:56.218 createdAt ------> 2014-10-14 13:45:39 +0000
  • 2014-12-08 00:00:56.224 createdAt ------> 2014-10-14 13:51:18 +0000
  • 2014-12-08 00:00:56.231 createdAt ------> 2014-09-04 09:56:27 +0000
  • 2014-12-08 00:00:56.233 createdAt ------> 2014-09-16 05:28:57 +0000
  • 2014-12-08 00:00:56.235 createdAt ------> 2014-10-23 07:34:15 +0000
  • 2014-12-08 00:00:56.237 createdAt ------> 2014-09-12 03:04:50 +0000
  • 2014-12-08 00:00:56.239 createdAt ------> 2014-09-16 05:12:59 +0000
  • 2014-12-08 00:00:56.246 createdAt ------> 2014-09-16 08:05:54 +0000
  • 2014-12-08 00:00:56.248 createdAt ------> 2014-09-10 06:01:19 +0000
  • 2014-12-08 00:00:56.250 createdAt ------> 2014-09-10 07:17:09 +0000
  • 2014-12-08 00:00:56.254 ( { createdAt = "10/14/2014"; text = "Www.thecubeinn.com.tw"; }, { createdAt = "10/14/2014"; text = "Www.thecubeinn.com.tw"; }, { createdAt = "09/04/2014"; text = "Mei Hua Hu Lake"; }, { createdAt = "09/16/2014"; text = Nanjuang; }, { createdAt = "10/23/2014"; text = "Carrefour, Neihu"; }, { createdAt = "09/12/2014"; text = "Yuangi brunch"; }, { createdAt = "09/16/2014"; text = "Surprisingly very good food here"; }, { createdAt = "09/16/2014"; text = "Nanliao harbor, hsinju"; }, { createdAt = "09/10/2014"; text = "Yana's home"; }, { createdAt = "09/10/2014"; text = "Wang long pei "; } )

Okay, so what you want to do is cycle through all of your items, and put them into buckets that are labeled by days (NSDictionary works well here - NSNumber can even be hashed as a key).

// Get the calendar for the user's locale
NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     [formatter setDateFormat:@"MM/dd/yyyy"];

// Sparse dictionary, containing keys for "days with posts"
NSMutableDictionary *daysWithPosts = [NSMutableDictionary dictionary];

[myPosts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    // use this if 'createdAt' is a UTC time-stamp
    // NSDate *date = [NSDate dateWithTimeIntervalSince1970:[obj createdAt].floatValue];
    // NSNumber *uniqueDay = @([calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitEra forDate:date]); // This is not fast

    NSString *dateString = [formatter stringFromDate:[obj createdAt]]; // EDIT 1

    // Check to see if we have a day already.
    NSMutableArray *posts = [daysWithPosts objectForKey: dateString /*uniqueDay*/];

    // If not, create it
    if (posts == nil || (id)posts == [NSNull null])
    {
        posts = [NSMutableArray arrayWithCapacity:1];
        [daysWithPosts setObject:posts forKey: dateString /*uniqueDay*/];
    }

    // add post to day
    [posts addObject:obj];
}];

// Sections array for TableView
NSArray *sectionTitles = [daysWithPosts allKeys]; // keep this around to re-format to strings?
NSArray *sections = [daysWithPosts allValues];

The result is an array of sections and titles which you can use in a Tableview.

id rowData = sections[indexPath.section][indexPath.row];

You may also want to sort the individual days further based on their individual time.

[sections enumeratObjectsUsingBlock:^(id obj, NSUinteger idx, BOOL *stop) {
    [(NSMutableArray*)obj sortUsingDescriptors:@[NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:YES]];
}];

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