Сеть синхронизации Parse.com с локальным хранилищем данных — проблема с закреплением и отсоединением

У меня есть настройка бэкэнда Parse, в которой у меня есть три класса:

  1. Пользователь
  2. Место - с информацией о ресторане
  3. SavedPlace — объект, моделирующий отношения User и Place с указателями как на User, так и на SavedPlace.

Я пытаюсь сделать так, чтобы я не мог синхронизировать мою сеть и локальное хранилище данных, но только там, где есть изменения, то есть только для объектов SavedPlace, которые отличаются в сети и локально (с использованием updateAt). Тем не менее, у меня возникают проблемы с закреплением и отсоединением, и я искал везде, включая следующий пост ниже, но, похоже, не могу его решить. Разбор локального хранилища данных + сетевая синхронизация

См. мой код для этой функции, где я хочу получить только обновленные объекты SavedPlace, открепить старые объекты в локальном хранилище данных и повторно закрепить их в хранилище данных.

Кажется, проблема заключается в том, что когда я повторно закрепляю обновленные объекты SavedPlace, полученные из сети, кажется, что объекты Place удаляются из локального хранилища данных. Как вы можете видеть на изображении ниже, есть закрепленные объекты SavedPlace и Place, а повторное закрепление объектов SavedPlace удаляет все объекты Place, кроме объекта SavedPlace, который я повторно закрепил.

SQLite локального хранилища данных

Как-то обойти это? Правильно ли я использую pinAllInBackground?

Благодарим вас за помощь в этом.

func fetchUpdatedSavedPlacesRemotelyAndPinLocally() {

    if let user = PFUser.currentUser(),
        let lastUpdateLocalDatastore = self.userDefaults.objectForKey("lastUpdateLocalDatastore") {

        // Fetch the places from Parse where lastUpdateDate in Parse is newer than the lastUpdateLocalDatastore
        print("Current lastupdateLocalDatastore: \(lastUpdateLocalDatastore)")
        let savedPlaceQueryParse = PFQuery(className: "SavedPlace")
        savedPlaceQueryParse.whereKey("user", equalTo: user)
        savedPlaceQueryParse.includeKey("place")
        savedPlaceQueryParse.includeKey("objectId")
        savedPlaceQueryParse.whereKey("updatedAt", greaterThanOrEqualTo: lastUpdateLocalDatastore)
        savedPlaceQueryParse.findObjectsInBackgroundWithBlock {
            (updatedSavedPlacesNetwork: [PFObject]?, error: NSError?) -> Void in
            if let updatedSavedPlacesNetwork = updatedSavedPlacesNetwork {
                if updatedSavedPlacesNetwork != [] {
                    print("Success - retrieved \(updatedSavedPlacesNetwork.count) updated places from Parse")

                    // Create an array of objectIds of the updated saved places to match against in the Local datastore
                    var updatedSavedPlaceObjectId = [String]()
                    for updatedSavedPlaceNetwork in updatedSavedPlacesNetwork {
                        updatedSavedPlaceObjectId.append(updatedSavedPlaceNetwork.objectId!)
                    }

                    // Fetch these updated saved places from the Local Datastore
                    let savedPlaceQuery = PFQuery(className: "SavedPlace")
                    savedPlaceQuery.fromLocalDatastore()
                    savedPlaceQuery.whereKey("user", equalTo: user)
                    savedPlaceQuery.includeKey("place")
                    savedPlaceQuery.includeKey("objectId")
                    savedPlaceQuery.whereKey("objectId", containedIn: updatedSavedPlaceObjectId)
                    savedPlaceQuery.findObjectsInBackgroundWithBlock {
                        (updatedSavedPlacesLocal: [PFObject]?, error: NSError?) -> Void in
                        if error == nil {
                            if let updatedSavedPlacesLocal = updatedSavedPlacesLocal {

                                // Unpin the updated saved places from the Local Datastore
                                PFObject.unpinAllInBackground(updatedSavedPlacesLocal) { (success: Bool, error: NSError?) -> Void in
                                    if (success) {
                                        print("Success - \(updatedSavedPlacesLocal.count) updated saved places unpinned from Local Datastore")

                                        // Pin the updated saved places from Parse to the Local Datastore and update the lastUpdateLocalDatastore
                                        PFObject.pinAllInBackground(updatedSavedPlacesNetwork) { (success: Bool, error: NSError?) -> Void in
                                            if (success) {
                                                print("Success - \(updatedSavedPlacesNetwork.count) updated saved places pinned to Local Datastore")
                                                self.userDefaults.setObject(NSDate(), forKey: "lastUpdateLocalDatastore")
                                                print("New lastUpdateLocalDatastore: \(self.userDefaults.objectForKey("lastUpdateLocalDatastore"))")
                                            }
                                            else {
                                                print("Fail - updated saved places not pinned and returned with error: \(error!.description)")
                                            }
                                        }
                                    }
                                    else {
                                        print("Fail - updated saved places not unpinned and returned with error: \(error!.description)")
                                    }
                                }
                            }
                        }
                        else {
                            print("Fail - updated saved places not fetched in Local Database and returned with error: \(error!.description)")
                        }
                    }
                }
                else {
                    print("No updates")
                }
            }
            else {
                print("Fail - load from Parse failed with error: \(error!.description)")
            }
        }
    }
}

person Danny    schedule 23.02.2016    source источник