使用coredata同步解析数据,如何确定要删除的对象?

时间:2015-07-19 23:31:43

标签: ios swift core-data parse-platform

我已成功编写代码来下载解析对象,获取数据库中的当前对象然后进行比较。

我的算法:

我遍历解析对象并运行fetchrequest并比较它们的objectID。如果什么都没有,我为我的数据库创建一个新对象。否则,我会查看我在数据库中的modifiedDate和来自parse的updatedAt并进行比较以查看是否需要设置新值。这段代码效果很好。

代码:

query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
    if error == nil {
        if let objects = objects {
            for object in objects {
                let object = object as! PFObject
                let name = object["name"] as! String
                let email = object["email"] as! String
                let subjectsTaught = object["subjectsTaught"] as [String: String]
                let category = object["category"] as! String
                let uniqueID = object.objectId!
                let modifiedDate = object.updatedAt!
                let fetchRequest2 = NSFetchRequest(entityName: "Teacher")
                fetchRequest2.predicate = NSPredicate(format: "uniqueID == %@", uniqueID)
                var error2: NSError?
                if let foundTeachers = self.managedObjectContext.executeFetchRequest(fetchRequest2, error: &error2) as? [Teacher] {
                    if foundTeachers.isEmpty == true {
                        let teacher = NSEntityDescription.insertNewObjectForEntityForName("Teacher", inManagedObjectContext: self.managedObjectContext) as! Teacher
                        teacher.name = name
                        teacher.email = email
                        teacher.subjectsTaught = subjectsTaught
                        teacher.category = category
                        teacher.uniqueID = uniqueID
                        teacher.modifiedDate = modifiedDate
                    } else {
                        if let teacher = foundTeachers.first {
                            let date1 = teacher.modifiedDate
                            let date2 = modifiedDate
                            let compareResult = date1.compare(date2)
                            if compareResult == NSComparisonResult.OrderedAscending {
                                teacher.setValue(name, forKey: "name")
                                teacher.setValue(email, forKey: "email")
                                teacher.setValue(subjectsTaught, forKey: "subjectsTaught")
                                teacher.setValue(category, forKey: "category")
                                teacher.setValue(modifiedDate, forKey: "modifiedDate")
                            }
                        }
                    }
                }
                var error: NSError?
                if !self.managedObjectContext.save(&error) {
                    println("Error \(error)")
                    abort()
                }
            }
        }

我的问题是我应该如何找出哪些对象不在解析中?我不想查询解析数据库中的每个对象,因为我认为这将是网络密集型的。

我应该在开始时为所有Teacher对象执行fetchrequest,当我遍历解析对象时,在我去的时候删除它们吗?如果我有剩下的对象,那些应该被删除?

2 个答案:

答案 0 :(得分:0)

好的,我想出了该怎么做。我最终为所有教师运行了一个fetchrequest,并将他们的名字附加到一个数组中。在解析迭代期间,我在浏览过程中删除了该列表中的教师,最后使用该列表从数据库中删除了教师。

        let fetchRequest = NSFetchRequest()
        fetchRequest.entity = NSEntityDescription.entityForName("Teacher", inManagedObjectContext: self.managedObjectContext)
        var error: NSError?
        var foundTeacherNames = [String]()
        if let foundTeachers = self.managedObjectContext.executeFetchRequest(fetchRequest, error: &error) as? [Teacher] {
            for teacher in foundTeachers {
                foundTeacherNames.append(teacher.name)
            }
        }
        //Find teachers in parse database
        let query = PFQuery(className: "TeacherList")
        query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
            if error == nil {
                if let objects = objects {
                    for object in objects {
                        let object = object as! PFObject
                        let name = object["name"] as! String
                        let email = object["email"] as! String
                        let subjectsTaught = object["subjectsTaught"] as! [String: String]
                        let category = object["category"] as! String
                        let uniqueID = object.objectId!
                        let modifiedDate = object.updatedAt!
                        let fetchRequest2 = NSFetchRequest(entityName: "Teacher")
                        fetchRequest2.predicate = NSPredicate(format: "uniqueID == %@", uniqueID)
                        var error2: NSError?
                        if let foundTeachers = self.managedObjectContext.executeFetchRequest(fetchRequest2, error: &error2) as? [Teacher] {
                            if foundTeachers.isEmpty == true {
                                let teacher = NSEntityDescription.insertNewObjectForEntityForName("Teacher", inManagedObjectContext: self.managedObjectContext) as! Teacher
                                teacher.name = name
                                teacher.email = email
                                teacher.subjectsTaught = subjectsTaught
                                teacher.category = category
                                teacher.uniqueID = uniqueID
                                teacher.modifiedDate = modifiedDate
                            } else {
                                if let teacher = foundTeachers.first {
                                    let date1 = teacher.modifiedDate
                                    let date2 = modifiedDate
                                    let compareResult = date1.compare(date2)
                                    if compareResult == NSComparisonResult.OrderedAscending {
                                        teacher.setValue(name, forKey: "name")
                                        teacher.setValue(email, forKey: "email")
                                        teacher.setValue(subjectsTaught, forKey: "subjectsTaught")
                                        teacher.setValue(category, forKey: "category")
                                        teacher.setValue(modifiedDate, forKey: "modifiedDate")
                                    }
                                }
                            }
                            if contains(foundTeacherNames, name) {
                                let i = find(foundTeacherNames, name)!
                                foundTeacherNames.removeAtIndex(i)
                            }
                        }
                        var error: NSError?
                        if !self.managedObjectContext.save(&error) {
                            println("Error \(error)")
                            abort()
                        }
                        if !foundTeacherNames.isEmpty {
                            for teacher in foundTeacherNames {
                                let request = NSFetchRequest(entityName: "Teacher")
                                request.predicate = NSPredicate(format: "name = %@", teacher)
                                if let fetchResults = self.managedObjectContext.executeFetchRequest(request, error: nil) as? [NSManagedObject] {
                                    if fetchResults.count != 0 {
                                        self.managedObjectContext.deleteObject(fetchResults[0])
                                    }
                                }

                            }
                        }

答案 1 :(得分:0)

是的,最好的方法是获取所有实体,然后检查唯一ID。您可以使用键值编码(或其Swift等价物,例如map)来获取您感兴趣的ID。

let existingIDs = entitiesFromParse.map() { $0.uniqueID as? String }

然后,您可以检查ID是否存在

let idExists = existingIDs.contains(idToCheck)

这比多个昂贵的提取请求更可取。