我想過濾和排序包含聊天消息列表的NSMutableArray。我正在嘗試獲取2個用戶之間對話的最後消息。例如,如果user1與2個不同的用戶有2個不同的會話,我想要獲得每個會話的最後一個消息。我使用Parse.com作爲後端,並且這是我保存&檢索到的消息。過濾包含消息列表的NSMutableArray
保存消息
PFUser *user = [[PFUser currentUser] objectForKey:@"displayName"];
PFObject *newMessage = [PFObject objectWithClassName:@"Messages"];
[newMessage setObject:messageStr forKey:@"body"];
[newMessage setObject:self.mySelectedUser forKey:@"toUser"];
[newMessage setObject:user forKey:@"fromUser"];
[newMessage saveInBackground];
myMessageField.text = @"";
[self getTheNewMessages];
[self.myTView reloadData];
檢索消息
-(void)GetmyNewMessages
{
PFQuery *query1 = [PFQuery queryWithClassName:@"Messages"];
[query1 whereKey:@"toUser" equalTo:[[PFUser currentUser] objectForKey:@"displayName"]];
[query1 whereKeyExists:@"date"];
PFQuery *query2 = [PFQuery queryWithClassName:@"Messages"];
[query2 whereKey:@"fromUser" equalTo:[[PFUser currentUser] objectForKey:@"displayName"]];
[query2 whereKeyExists:@"date"];
PFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:query1, query2, nil]];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSLog(@"Successfully retrieved %d chats.", objects.count);
[premessagesList removeAllObjects];
[premessagesList addObject:objects];
} else {
//Log details of the failure
NSLog(@"Error: %@ %@", error, [error userInfo]);
}
}];
}
的NSLog所述的NSMutableArray(premessageList)的
("<Messages:aS8tVIlsHc:(null)> {\n
body = hi;\n fromUser = cnn;\n toUser =FNC;\n
date = \"2012-09-19 02:40:29 +0000\";\n}",
"<Messages:CPCa6VBmf7:(null)> {\n
body = hello;\n fromUser = FNC;\n toUser =cnn;\n
date = \"2012-09-20 05:06:05 +0000\";\n}",
"<Messages:Jz1cILt18Y:(null)> {\n
body = whatsgood;\n fromUser = sleepy;\n toUser =cnn;\n
date =\"2012-09-20 05:06:05 +0000\";\n}",
"<Messages:lXretmE1uK:(null)> {\n
body = lol;\n fromUser = cnn;\n toUser =sleepy;\n
date =\"2012-09-20 05:13:16 +0000\";\n}",
我試圖使用NSSortDescriptor和NSPredicate,但我得到了一個空的tableview。