x = [1, 10, 100] for i in x: print '%02d' % i
результаты в:
01 10 100
Read больше информации о строковом форматировании с помощью % в документации.
Сохраните даты как объекты NSDate
в NS (Mutable ) Array, затем используйте - [NSArray sortedArrayUsingSelector:
или - [NSMutableArray sortUsingSelector:]
и передайте @selector (compare:)
в качестве параметра. Метод - [NSDate compare:]
упорядочит даты в порядке возрастания. Это проще, чем создание NSSortDescriptor
, и намного проще, чем написание вашей собственной функции сравнения. ( Объекты NSDate
знают, как сравнивать себя друг с другом, по крайней мере так эффективно, как мы могли бы надеяться достичь с помощью специального кода.)
You can use sortedArrayUsingFunction:context:
. Here is a sample:
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
NSDate *d1 = [NSDate dateWithString:s1];
NSDate *d2 = [NSDate dateWithString:s2];
return [d1 compare:d2];
}
NSArray *sorted = [unsorted sortedArrayUsingFunction:dateSort context:nil];
When using a NSMutableArray
, you can use sortArrayUsingFunction:context:
instead.
Once you have an NSDate
, you can create an NSSortDescriptor
with initWithKey:ascending:
and then use sortedArrayUsingDescriptors:
to do the sorting.