I have a class on parse.com, that contains many objects. One of the keys of each object, is the name of a country. How can I programatically delete all objects with a repeated country name key. The only way I can think of is very longwinded, so any ideas would be greatly appreciated.
This is the best I could come up with.
var objectId = [String]()
var Country = [String]()
var city = [String]()
var deletes = [String]()
var query = PFQuery(className: "Route")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
for object in objects {
objectId.append(object.objectId)
Country.append(object["Country"] as String)
city.append(object["Start"] as String)
}
println(objectId)
println(Country)
var i = Int()
for i=0; i < objectId.count; i++ {
var j = Int()
for j = i + 1 ; j < objectId.count; j++ {
if Country[i] == Country[j] {
println(objectId[j])
var deleteQuery = PFQuery(className: "Route")
deleteQuery.getObjectInBackgroundWithId(objectId[j], block: { (object: PFObject!, error2: NSError!) -> Void in
if error2 == nil {
object.delete()
}
})
}
}
}
}
I'm convinced there must be a simpler way.
I think you could make the duplicate search a little skinnier by creating an NSMutableSet
of country names. Run through the returned objects adding the country names to the set, testing membership beforehand. If a an object's country is in the set already, add it to a mutable array of of duplicates
.
The deletion part of your code can be much improved. After the set-based test fills the duplicates array, use PFObject(deleteAllInBackground:duplicates)
This will replace all of the code beginning at for i=0; i < objectId.count; i++ {