我正在开发聊天类应用程序。我从服务器获取完整的消息列表并将其保存到自定义实体NSObject类的数组中。
这是我的class.h:
@interface ChatMessage : NSObject
@property (nonatomic, retain) NSString *msg_text;
@property (nonatomic, retain) NSDate *msg_date;
@property (nonatomic, assign) int sender_id;
@property (nonatomic, assign) int receiver_id;
@property (nonatomic, retain) NSString *msg_status;
@end
这是我的class.m:
#import "ChatMessage.h"
@implementation ChatMessage
@synthesize msg_text, msg_date, msg_status, sender_id, receiver_id;
- (id) initWithCoder: (NSCoder *)coder
{
self = [[ChatMessage alloc] init];
if (self != nil)
{
self.msg_text = [coder decodeObjectForKey:@"msg_text"];
self.msg_date = [coder decodeObjectForKey:@"msg_date"];
self.msg_status = [coder decodeObjectForKey:@"msg_status"];
self.sender_id = [coder decodeIntForKey:@"sender_id"];
self.receiver_id = [coder decodeIntForKey:@"receiver_id"];
}
return self;
}
- (void)encodeWithCoder: (NSCoder *)coder
{
[coder encodeObject:msg_text forKey:@"msg_text"];
[coder encodeObject:msg_date forKey:@"msg_date"];
[coder encodeObject:msg_status forKey:@"msg_status"];
[coder encodeInt:sender_id forKey:@"sender_id"];
[coder encodeInt:receiver_id forKey:@"receiver_id"];
}
@end
我想在我的CellForRowAtIndexPath中使用“msg_date”属性对NSMutableArray的对象进行排序,然后将其显示到我的聊天列表表视图中。我将每条聊天消息的日期和时间格式设置为“2014-08-21 18:30:00”。
这是我的用于排序对象数组的代码:
NSMutableArray *unsortedArray = [[NSMutableArray alloc] init];
//sorting array with date and time
for (int i=0; i<[self.arrayChatMessages count]; i++) {
ChatMessage *chat = [[ChatMessage alloc] init];
chat = [self.arrayChatMessages objectAtIndex:i];
[unsortedArray addObject:chat.msg_date];
}
NSLog(@"un sorted array is = %@", unsortedArray);
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
NSLog(@"sorted array is = %@", sortedArray);
它正在成功排序。在我的控制台中,我得到了:
un sorted array is = (
"2014-08-21 18:28:58",
"2014-08-21 18:27:41",
"2014-08-21 20:10:45",
"2014-08-21 18:30:45",
"2014-08-29 12:27:45"
)
sorted array is = (
"2014-08-29 12:27:45",
"2014-08-21 20:10:45",
"2014-08-21 18:30:45",
"2014-08-21 18:28:58",
"2014-08-21 18:27:41"
)
我的问题是根据这个排序的数组,我如何排序对象数组,即self.arrayChatMessages。
答案 0 :(得分:1)
要对NSArray
个自定义对象进行排序,您可以使用-sortedArrayUsingComparator:
方法并依赖-compare:
NSString
方法的结果:
self.arrayChatMessages = [self.arrayChatMessages sortedArrayUsingComparator:^(ChatMessage *obj1, ChatMessage *obj2) {
return [obj1.msg_date compare:obj2.msg_date];
}];
另外,我建议您使用NSString
将日期属性从NSDate
转换为NSDateFormatter
。