简体   繁体   中英

Using NSSortDescriptor to sort objects in NSMutableArray iOS?

I have an NSMutableArray of Objects. I need to sort them based on createdDate and name. Below is the scenario which i am facing: File Names are like this: Image.pdf, Image 1.pdf, Image 2.pdf, Image 3.pdf, Image 4.pdf, Image 5.pdf...

Now these files can have same createdDate so when createdDate is same then it should be sorted by name in descending order. So if above files have same created date then after sorting it should be displayed as: Image 5.pdf, Image 4.pdf, Image 3.pdf, Image 2.pdf, Image 1.pdf, Image.pdf but when i use below code Image.pdf is jumbled or displayed like this: Image.pdf, Image 5.pdf, Image 4.pdf, Image 3.pdf, Image 3.pdf, Image 1.pdf

NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"createdDate" ascending:NO selector:@selector(compare:)];
    NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO selector:@selector(localizedStandardCompare:)];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil];
    return sortDescriptors;

我猜您的逻辑有误,首先您必须检查所有文件的日期是否相同,如果它们具有相同的日期,则仅按名称排序,否则按日期排序。

String representation of integers give undefined behavior, so when you are comparing @"Image 1.pdf" < @"Image 2.pdf" , will have an undefined behavior.

What you can do is try to first get that number which is appended to "Image" and then try to sort it.

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