ios - 使用 NSSortDescriptor 通过 setDateFomat :@"dd. MMMM-EEEE 对 UITableview 标题进行排序

标签 ios objective-c uitableview nssortdescriptor

我在 UITableView 中有一个标题,其日期不同,格式为 dd.MMMM-EEEE。如何根据时间从旧到新对它们进行排序?我应该使用 NSSortDescriptor 吗?

这是我的代码:

@synthesize managedObjectContext, pictureListData;
@synthesize scroll;

-(IBAction)scrolldown:(id)sender{
    NSCalendar *cal = [NSCalendar currentCalendar];

    NSDate *today = [NSDate date];
    NSInteger index = NSNotFound;
    if ([pictureListData containsObject:today]) {
        index = [pictureListData indexOfObject:today];
    }

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView scrollToRowAtIndexPath:indexPath
                          atScrollPosition:UITableViewScrollPositionNone
                                  animated:YES];
}
-(void)viewDidLoad{
    NSSortDescriptor * sortDesc = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
    [pictureListData sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
        [self.tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated
{
    //  Repopulate the array with new table data
    [self readDataForTable];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd.MMMM - EEEE"];
    NSDate *today = [NSDate date];
    [pictureListData  enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        Pictures *picture = (Pictures *)obj;
        NSDate *date = [dateFormatter dateFromString:picture.title];
        NSDateComponents *components = [cal components:NSDayCalendarUnit
                                              fromDate:date
                                                toDate:today
                                               options:0];
        if ([components day]==0) {
            *stop = TRUE;
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath
                                  atScrollPosition:UITableViewScrollPositionTop
                                          animated:YES];
        }
    }];
}
//  When the view reappears, read new data for table


//  Grab data for table - this will be used whenever the list appears or reappears after an add/edit
- (void)readDataForTable
{
    //  Grab the data
    pictureListData = [CoreDataHelper getObjectsForEntity:@"Pictures" withSortKey:@"title" andSortAscending:YES andContext:managedObjectContext];

    //  Force table refresh
    [self.tableView reloadData];
}

#pragma mark - Actions

//  Button to log out of app (dismiss the modal view!)


#pragma mark - Segue methods

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    //  Get a reference to our detail view
    PictureListDetail *pld = (PictureListDetail *)[segue destinationViewController];

    //  Pass the managed object context to the destination view controller
    pld.managedObjectContext = managedObjectContext;

    //  If we are editing a picture we need to pass some stuff, so check the segue title first
    if ([[segue identifier] isEqualToString:@"EditPicture"])
    {
        //  Get the row we selected to view
        NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];

        //  Pass the picture object from the table that we want to view
        pld.currentPicture = [pictureListData objectAtIndex:selectedIndex];
    }
}

#pragma mark - Table view data source

//  Return the number of sections in the table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//  Return the number of rows in the section (the amount of items in our array)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [pictureListData count];
}

//  Create / reuse a table cell and configure it for display
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Get the core data object we need to use to populate this table cell
    Pictures *currentCell = [pictureListData objectAtIndex:indexPath.row];

    //  Fill in the cell contents
    cell.textLabel.text = [currentCell title];
    cell.detailTextLabel.text = [currentCell desc];

    //  If a picture exists then use it
    if ([currentCell smallPicture])
    {
        cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
        cell.imageView.image = [UIImage imageWithData:[currentCell smallPicture]];
    }

    return cell;
}

//  Swipe to delete has been used.  Remove the table item
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //  Get a reference to the table item in our data array
        Pictures *itemToDelete = [self.pictureListData objectAtIndex:indexPath.row];

        //  Delete the item in Core Data
        [self.managedObjectContext deleteObject:itemToDelete];

        //  Remove the item from our array
        [pictureListData removeObjectAtIndex:indexPath.row];

        //  Commit the deletion in core data
        NSError *error;
        if (![self.managedObjectContext save:&error])
            NSLog(@"Failed to delete picture item with error: %@", [error domain]);

        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
}

@end

最佳答案

修改您的数据源初始化方法。常规 sortDescriptor 是不够的,因为您需要将 dateString 更改为日期以进行比较。

- (void)readDataForTable
{
    //  Grab the data
    pictureListData = [CoreDataHelper getObjectsForEntity:@"Pictures" withSortKey:@"title" andSortAscending:YES andContext:managedObjectContext];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"dd.MMMM - EEEE"];

    [pictureListData sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {

        Pictures *picture1 = (Pictures *)obj1;
        Pictures *picture2 = (Pictures *)obj2;

        NSDate *date1 = [dateFormatter dateFromString:picture1.title];
        NSDate *date2 = [dateFormatter dateFromString:picture2.title];

        return [date1 compare:date2];
    }];

    //  Force table refresh
    [self.tableView reloadData];
}

关于ios - 使用 NSSortDescriptor 通过 setDateFomat :@"dd. MMMM-EEEE 对 UITableview 标题进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16124215/

相关文章:

iphone - 在 iOS 中检查互联网连接的最简单方法是什么?

ios - 搜索时状态栏消失

ios - 加载时标签栏中的项目不可见

ios - 在 Storyboard 中创建和使用自定义 UITableViewCell 模板

ios - 使用快速 channel 匹配时,配置文件 “match x” 不包括签名证书 “Apple Distribution: Company (ID)”

javascript - Parse.com 云代码调度每 n 分钟

objective-c - iOS8 - 约束含糊地暗示高度为零

objective-c - NSTextField - *textField 内的操作

ios - 碰巧不以 fileURLWithPath 文件夹中的资源为目标

ios - 如何隐藏IOS键盘上的返回键