问题
I am working on a chat application and using xmppframework .Now there is a need for storing message in a persistent storage. Can anyone tell me how can i store and retrieve message from CoreData in IOS.
回答1:
Since you're using github/robbiehanson/XMPPFramework, it's easy to get both your incoming and outgoing message stored during initializing:
//this code init your XMPPStream
xmppStream = [[XMPPStream alloc]init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
xmppStream.autoStartTLS = YES;
xmppReconnect = [[XMPPReconnect alloc]init];
[xmppReconnect activate:self.xmppStream];
xmppMessageArchivingCoreDataStorage = [XMPPMessageArchivingCoreDataStorage sharedInstance];
xmppMessageArchivingModule = [[XMPPMessageArchiving alloc]initWithMessageArchivingStorage:xmppMessageArchivingCoreDataStorage];
[xmppMessageArchivingModule setClientSideMessageArchivingOnly:YES];
[xmppMessageArchivingModule activate:xmppStream]; //By this line all your messages are stored in CoreData
[xmppMessageArchivingModule addDelegate:self delegateQueue:dispatch_get_main_queue()];
To retrieve the saved message, here's the sample code in my project:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [self.xmppMessageArchivingCoreDataStorage mainThreadManagedObjectContext];
NSEntityDescription *messageEntity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:context];
fetchRequest.entity = messageEntity;
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
//Now you get the NSArray with element type of "XMPPMessageArchiving_Message_CoreDataObject"
回答2:
Are you using https://github.com/robbiehanson/XMPPFramework If yes then it by defaults implements core data and you just have to make minor changes to get the chat message...
来源:https://stackoverflow.com/questions/20609824/saving-xmppmessage-in-coredata-in-xmppframework-ios