我的对象有时间戳和文本,时间戳是在保存之前格式化为NSString的NSDate。创建新对象并设置其值后,我保存它。稍后加载它时我将所有对象放入一个数组并将该数组与另一个数组混合,这就是我需要对数组进行排序的原因。
我的问题是:我不知道如何通过对象正确对数组进行排序时间戳属性。
我一直在搜索,但仍然没有最新的答案。任何帮助表示赞赏。
答案 0 :(得分:2)
要比较两个不同的时间戳,首先必须将其转换为NSData:
-(NSDate)convertToDate:(NSString*)inputDate
//NSString *inputDate = @"11/20/2013 3:30:05 PM"; //<-- Your date probably is different than that
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
dateFormatter1.dateFormat = @"MM/dd/yyyy hh:mm:ss a"; //<-- this needs to be changet to match your time stamp format
[dateFormatter1 setLocale:[NSLocale currentLocale]];
NSDate *date = [dateFormatter1 dateFromString:inputDate]; //<- this is your NSDate object.
return date;
}
NSArray *sortedArray = [unSortedArray sortedArrayUsingComparator: ^NSComparisonResult(DateObj *id1, DateObj *id2) {
NSDate d1 = [self convertToDate:id1.timeStamp];
NSDate d2 = [self convertToDate:id2.timeStamp];
return [d1 compare:d2];
}];
您还可以向您的班级添加比较方法,例如:
- (NSComparisonResult)compare:(YourClass *)obj
{
NSDate d1 = [self convertToDate:self.timeStamp];
NSDate d2 = [self convertToDate:obj.timeStamp];
return [d1 compare:d2];
}
如果您需要对此对象的数组进行排序,请调用:
NSArray *sortedArray = [yourArray sortedArrayUsingSelector:@selector(compare:)];
答案 1 :(得分:0)
试试这个;
NSArray *sortedArray = [unSortedArray sortedArrayUsingComparator: ^NSComparisonResult(DateObj *id1, DateObj *id2) {
if(id1.timeStamp > id2.timeStamp)
return NSOrderedAscending;
else if (id1.timeStamp < id2.timeStamp)
return NSOrderedDescending;
else return NSOrderedSame;
}];
您将获得有关排序HERE的更多信息。
答案 2 :(得分:0)
我的解决方案:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.YYYY HH:mm:ss"];
NSMutableArray *timeStamps = [[NSMutableArray alloc] init];
for(Object *object in allObjects) {
NSDate *time = [dateFormatter dateFromString:object.timeStamp];
[timeStamps addObject:time];
}
[timeStamps sortedArrayUsingSelector:@selector(compare:)];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:[allObjects count]];
for(int i = 0; i < [timeStamps count]; i++) {
for(Object *object in allObjects) {
if(object.timeStamp == [dateFormatter stringFromDate:timeStamps[i]]) {
[sortedArray addObject:messageObject];
}
}
}
return sortedArray;