自定义类排序属性,NSDate 在 Objective-C 中不起作用



我用FileModel创建自定义类名。

 FileModel.h
 #import <Foundation/Foundation.h>
 @interface FileModel : NSObject
 @property (nonatomic, copy)   NSString *fileName;
 @property (nonatomic, copy)   NSString *fileType;
 @property (nonatomic, strong) NSDate   *editDate;
 @property (nonatomic, assign) NSInteger fileSize;
 @end

我想使用 editDate 对文件模型进行排序,但它不起作用。

我创建如下所示的示例.m

- (void)viewDidLoad {
    [super viewDidLoad];
         NSArray *fileSampleName = [[NSArray alloc] initWithObjects:@"apple.png",@"banana.png",@"cherry.png",@"durian.png",@"grape.png",@"avocado.png", nil];
         NSMutableArray *fileData = [NSMutableArray new];
         FileModel *fileModel = nil;
         for( NSInteger i = 0 ; i < fileSampleName.count  ; i++){
             fileModel = [FileModel new];
             fileModel.fileName = [fileSampleName objectAtIndex:i];
             fileModel.fileType = @"photo";
             fileModel.fileSize = 0;
             fileModel.editDate = [NSDate new];
             [fileData addObject:fileModel];
             // test for nsdate interveral
             [NSThread sleepForTimeInterval:1];
         }
         NSArray *sortedArray;
         sortedArray = [fileData      sortedArrayUsingComparator:^NSComparisonResult(FileModel *a, FileModel *b)      {
             NSDate *first = [(FileModel*)a editDate];
             NSDate *second =  [(FileModel*)a editDate];
             return [second compare:first];
         }];
         NSLog(@"sortedArray:%@",sortedArray);
         // log
         for (FileModel *fm in sortedArray) {
             NSLog(@"sortedArray:%@", fm.fileName);
         }
     }

为什么我 NSLog 排序顺序不是

鳄梨.png ->葡萄.png->榴莲.png->樱桃.png->香蕉.png-> 苹果.png

谢谢。

你错过了在第二个变量中再次键入 a 而不是 b

  NSArray *sortedArray;
  sortedArray = [fileData   sortedArrayUsingComparator:^NSComparisonResult(FileModel *a, FileModel *b)      {
    NSDate *first = [(FileModel*)a editDate];
    NSDate *second =  [(FileModel*)b editDate];
    return [second compare: first];
   }];

试试这个

NSArray *sortArray = [fileData sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    NSDate *first = [(FileModal*)obj1 editDate];
    NSDate *second =  [(FileModal*)obj2 editDate];
    return !([first compare:second] == NSOrderedDescending);
}];

相关内容

最新更新