Orkhan Alizade
Orkhan Alizade

Reputation: 7549

How to delete chats from XMPP Message Storage?

I have an open chats controller and I want to delete them from my device.

I try this code:

let moc = OneMessage.sharedInstance.xmppMessageStorage?.mainThreadManagedObjectContext
    let entityDescription = NSEntityDescription.entityForName("XMPPMessageArchiving_Message_CoreDataObject", inManagedObjectContext: moc!)
    let request = NSFetchRequest()
    let predicateFormat = "bareJidStr like %@ "

    let predicate = NSPredicate(format: predicateFormat, user.jidStr)
    request.predicate = predicate
    request.entity = entityDescription

    do {
        let results = try moc?.executeFetchRequest(request)
        print("Results: \(results)")
        for message in results! {
            print("Message is: \(message)")
            moc?.deleteObject(message as! NSManagedObject)
        }
    } catch _ {
    }

BUT when I remove them, in logs I see, that they have been deleted, but when I relaunch my app, they are appear again. So, it delete them just for a moment, until the app restart.

What is wrong here? Can anyone help me with this bug?

If you have a questions, you can ask me in comments, please

Upvotes: 2

Views: 1157

Answers (1)

Utkarsh Singh
Utkarsh Singh

Reputation: 181

You have a separate NSManagedObjectContext of XMPPMessageArchiving entity for the changes you're about to perform on the database.

There's nothing wrong with your code, it's happening because you're deleting objects but your are not performing save operation, send save and perform the whole mergeChangesFromContextDidSaveNotification.

in your case it should be:

Swift:

do {
    let results = try moc?.executeFetchRequest(request)
    print("Results: \(results)")
    for message in results! {
        print("Message is: \(message)")
        moc?.deleteObject(message as! NSManagedObject)
    }

    moc.save(nil) /** This line will update the main database **/

} catch _ {
}

Objective C:

NSError *error;
NSArray *fetchedObjects = [moc executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *object in fetchedObjects) {
    [moc deleteObject:object];
}

if (![moc save:&error]) {
    NSLog(@"Error in deleting conversation thread %@", error);
}

Upvotes: 1

Related Questions