i have entity named messages
following attributes: -> message_id
, message_from
, message_to
, message_body
, date_created
.
i want fetch last message
each user have in whatsapp chat.
i found following code mysql
, don't know how use nspredicates
:
select * messages m1 date_created = (select max(m2.date_created) messages m2 m1.message_from = m2.message_from , m1.message_to = m2.message_to)
could please me last message each user core data using nspredicate
?
first of need method extracts messages , users. simplicity put in appdelegate.m. note getallmessages gets unique results extracting data nsdictionary definition not allow duplicate keys
-(nsarray*)getallusers { // initializing nsfetchrequest nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; //setting entity queried nsentitydescription *entity = [nsentitydescription entityforname:@"message" inmanagedobjectcontext:self.managedobjectcontext]; fetchrequest.resulttype = nsdictionaryresulttype; fetchrequest.returnsdistinctresults = yes; [fetchrequest setentity:entity]; [fetchrequest setpropertiestofetch:@[@"userid"]]; fetchrequest.sortdescriptors = @[[nssortdescriptor sortdescriptorwithkey:@"date_created" ascending:no]]; nserror* error; // query on managedobjectcontext generated fetchrequest nsarray *fetchedrecords = [self.managedobjectcontext executefetchrequest:fetchrequest error:&error]; // returning fetched records return fetchedrecords; } -(nsarray*)getallmessages { // initializing nsfetchrequest nsfetchrequest *fetchrequest = [[nsfetchrequest alloc] init]; //setting entity queried nsentitydescription *entity = [nsentitydescription entityforname:@"message" inmanagedobjectcontext:self.managedobjectcontext]; fetchrequest.sortdescriptors = @[[nssortdescriptor sortdescriptorwithkey:@"date_created" ascending:no]]; [fetchrequest setentity:entity]; nserror* error; // query on managedobjectcontext generated fetchrequest nsarray *fetchedrecords = [self.managedobjectcontext executefetchrequest:fetchrequest error:&error]; // returning fetched records return fetchedrecords; }
then can extract , put last message each user in nsmutablearray doing this:
appdelegate * appdelegate = (appdelegate *)[[uiapplication sharedapplication] delegate]; nsmutablearray * arrayusers = [nsmutablearray arraywitharray:[appdelegate getallusers]]; nsmutablearray * arraymessages = [nsmutablearray arraywitharray:[appdelegate getallmessages]]; nsmutablearray * lastmessageforeachuser = [nsmutablearray array];//on array results (nsdictionary * dict in arrayusers) { nsnumber * userid = [dict objectforkey:@"userid"]; nspredicate * pr = [nspredicate predicatewithformat:@"userid == %@",userid]; nsarray * results = [arraymessages filteredarrayusingpredicate:pr]; message * lastmessage = results.count>0 ? [results objectatindex:0] : nil; [lastmessageforeachuser addobject:lastmessage]; }
Comments
Post a Comment