我在项目中创建了两个名为NSManagedObject
和Contact
的{{1}}。两个对象都有一个名为Groups
的属性。
我有一个包含两个对象的数组。
我希望按timeLastMessageReceived
的时间顺序排列数组。
timeLastMessageReceived
我正在尝试这种方法:
@interface Contact : NSManagedObject
...
@property (nonatomic, retain) NSDate * timeLastMessageReceived;
@property (nonatomic, retain) NSString * lastMessage;
@end
@interface Groups : NSManagedObject
@property (nonatomic, retain) NSDate * timeLastMessageReceived;
@property (nonatomic, retain) NSString * lastMessage;
@end
但它因错误而崩溃: - NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSArray *newArr = [self.chatArray sortedArrayWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = obj1[@"timeLastMessageReceived"];
NSDate *date2 = obj2[@"timeLastMessageReceived"];
return [date1 compare:date2];
}];
有任何想法吗。感谢。
答案 0 :(得分:2)
更新回答:
作为替代方案,您可以使用排序描述符对数组进行排序:
NSSortDescriptor *timeLastMessageReceivedDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeLastMessageReceived" ascending:YES];
NSArray *sortDescriptors = @[timeLastMessageReceivedDescriptor];
NSArray *sortedArray = [self.chatArray sortedArrayUsingDescriptors:sortDescriptors];
原始回答:
我猜self.chatArray
包含Contact
类型的实例?您应该能够像那样实现比较器:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSArray *newArr = [self.chatArray sortedArrayWithOptions:0 usingComparator:^NSComparisonResult(Contact *contact1, Contact *contact2) {
NSDate *date1 = contact1.timeLastMessageReceived;
NSDate *date2 = contact2.timeLastMessageReceived;
return [date1 compare:date2];
}];
答案 1 :(得分:1)
您可以在[]
的实例上使用-objectForKeyedSubscript:
运算符(即NSDictionary
)。正如错误消息所述,您正在处理Contact
的实例,因此它不支持下标运算符。
您展示了timeLastMessageReceived
仅仅是Contact
上的属性的方式,因此您应该能够使用默认的属性访问语法:
NSDate *date1 = obj1.timeLastMessageReceived;
NSDate *date2 = obj2.timeLastMessageReceived;
答案 2 :(得分:1)
我将创建一个由Contact和Group实现的协议,它定义timeLastMessageReceived
属性。
@protocol ContactOrGroupProtocol
@property (nonatomic, retain) NSDate * timeLastMessageReceived;
@end
然后,比较器块将是:
^NSComparisonResult(id<ContactOrGroupProtocol> obj1, id<ContactOrGroupProtocol> obj2) {
NSDate *date1 = obj1.timeLastMessageReceived;
NSDate *date2 = obj2.timeLastMessageReceived;
return [date1 compare:date2];
}];
答案 3 :(得分:0)
另一种方法是在班级Groups
和Contact
- (NSComparisonResult)compareLastMessageReceived:(Groups *)group {
return [self.timeLastMessageReceived compare:group.timeLastMessageReceived];
}
- (NSComparisonResult)compareLastMessageReceived:(Contact *)contact {
return [self.timeLastMessageReceived compare:contact.timeLastMessageReceived];
}
并致电sortedArrayUsingSelector:
NSArray *newArr = [self.chatArray sortedArrayUsingSelector:@selector(compareLastMessageReceived:)];