我正在處理聊天類應用程序。在哪裏我從服務器獲取完整的消息列表並將其保存到自定義實體NSObject類的數組中。錯誤:使用日期和時間屬性對NSMutableArray對象進行排序?
這裏是我的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
我想要做的對象的排序NSMutableArray在我的CellForRowAtIndexPath中使用「msg_date」屬性,然後將其顯示到我的聊天列表表格視圖中。我爲每個聊天消息獲取日期和時間格式爲「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的陣列。
http://stackoverflow.com/questions/1132806/sort-nsarray-of-date-strings-or-objects檢查這是否有幫助,不要忘記upvote如果它工作提供的答案 – channi 2014-08-29 07:19:16
Thanks @ channiI檢查了這個鏈接,但在我的情況下,而不是數組的日期和時間,我有自定義對象的數組。我的日期和時間是單個字符串值,我正在使用CellForRowAtindexPath表格方法。 – 2014-08-29 07:23:40