我声明了2个NSMutableArrays。一个填充了名称,然后另一个填充了NSDate的字符串值。
我想根据第二个日期中的日期对它们进行排序。例如,如果日期数组中的元素3变为元素0,我希望名称数组发生相同的事情。
最简单的方法是什么?我知道如何排序日期数组只是不对应的名称数组! (Objective-C Please!)
答案 0 :(得分:0)
对2个数组进行排序并使它们保持同步是一件痛苦的事。你基本上必须手工排序。
最简单的方法可能是创建一个字典数组,其中每个字典都包含数据和名称。
然后按日期对字典数组进行排序。
以下是创建包含名称和日期的自定义对象的代码。有按日期排序的代码以及按名称排序的代码:
/**
The thing class has a property date and a property name.
It is purely for creating sorted arrays of objects
*/
@interface Thing : NSObject
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, strong) NSString *name;
@end
@implementation Thing
/**
This is a dummy init method that creates a Thing ojbect with a random name and date
*/
- (instancetype) init {
self = [super init];
if (!self) return nil;
NSString *letters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
NSMutableString *temp = [NSMutableString new];
for (int x = 0; x < 10; x++) {
unichar aChar = [letters characterAtIndex:arc4random_uniform(26)];
[temp appendFormat: @"%C", aChar];
}
self.name = [temp copy];
//Create a random date
uint32 halfMax = 2000000000;
uint32 max = halfMax * 2;
int32_t value = arc4random_uniform(max) - halfMax;
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
self.date = [NSDate dateWithTimeIntervalSinceReferenceDate: now + value];
return self;
}
- (NSString *) description {
return [NSString stringWithFormat: @"Name: %@ Date: %@", self.name, self.date];
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
//Create an array of Thing objects
const int count = 50;
NSMutableArray *thingArray = [NSMutableArray arrayWithCapacity: count];
for (int x = 0; x < count; x++) {
thingArray[x] = [[Thing alloc] init];
}
#if 1
//Sort by date, ascending
[thingArray sortUsingComparator:^NSComparisonResult(Thing *obj1,
Thing *obj2) {
NSComparisonResult bigger =
[obj1.date timeIntervalSinceReferenceDate] <
[obj2.date timeIntervalSinceReferenceDate] ?
NSOrderedAscending : NSOrderedDescending;
return bigger;
}];
#else
//Sort by name
[thingArray sortUsingComparator:^NSComparisonResult(Thing *obj1,
Thing *obj2) {
return [obj1.name compare: obj2.name];
}];
#endif
NSLog(@"%@", thingArray);
}
return 0;
}