过滤包含消息列表的NSMutableArray

时间:2012-09-25 23:29:47

标签: ios uitableview nspredicate nssortdescriptor

我正在尝试过滤和排序包含聊天消息列表的NSMutableArray。我正在尝试获取2个用户之间的对话的最后消息。例如,如果user1与2个不同的用户有2个不同的对话,我想获得每个对话的最后一条消息。我正在使用Parse.com作为后端,这就是我如何保存&检索邮件。

保存邮件

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]);


        }


    }];

}

NSMutableArray的NSLog(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。

2 个答案:

答案 0 :(得分:0)

在这类问题中,我会使用一些变量和快速迭代来浏览信息并得到你需要的东西:

id lastChat = ni;
... temps 

for(OneChat in allChats) {
  do tests and set variables
}

Now I know the last chat.
PS:我决定不发布这个,但是当我看到很长一段时间没有人回应后觉得它总比没有好。这就是我解决这个问题的方法。

答案 1 :(得分:0)

您可以限制结果并按照PFQuery本身进行排序:

[query1 orderByDescending:@"createdAt"];
query1.limit = 1;
[query2 orderByDescending:@"createdAt"];
query2.limit = 1;