我试图通过查询用户和项目的两个对象来防止重复项目被复制。如果它们存在则不重复但如果它不存在则创建它的实例。我知道它会继续运行,并根据解析中的项目数量生成多个重复项。有谁知道如何防止它重复这些值?
func addUserToItem(userID:String,myItemID:String,currCommit:Float) {
let query = PFQuery(className: "UserToItem")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error != nil {
print("Got an error here")
} else {
print(objects)
for object in objects! {
print("ok")
guard let userInformation = object.objectForKey("username") as? String else {
print("didnt work")
return
}
guard let itemInformation = object.objectForKey("currentItem") as? String else {
print("didnt work2")
return
}
var isThere = false
if (userInformation == userID) && (itemInformation == myItemID) {
print("It exists")
isThere = true
}
if !isThere {
print("it worked")
let myProduct = PFObject(className: "UserToItem")
myProduct.setObject(userID, forKey: "username")
myProduct.setObject(myItemID, forKey: "currentItem")
myProduct.setObject(currCommit, forKey: "UserCommit")
myProduct.setObject(true, forKey: "Viewed")
myProduct.saveInBackground()
isThere = true
}
}
}
})
}
答案 0 :(得分:0)
您可以将NSSet用于存储唯一对象。
答案 1 :(得分:0)
我并不是要回答我自己的问题,但我明白了。它现在正按计划运作。这是我的代码。它现在可以正常工作,但是我再次尝试我的早期解决方案,但事后并没有。这看起来对每个人都有好处吗?这会让我后来头痛吗?
func addUserToItem(userID:String,myItemID:String,currCommit:Float) {
let query = PFQuery(className: "UserToItem")
query.whereKey("username", equalTo: userID)
query.whereKey("currentItem", equalTo: myItemID)
query.getFirstObjectInBackgroundWithBlock { (object, error) -> Void in
if error != nil {
let myProduct = PFObject(className: "UserToItem")
myProduct.setObject(userID, forKey: "username")
myProduct.setObject(myItemID, forKey: "currentItem")
myProduct.setObject(currCommit, forKey: "UserCommit")
myProduct.setObject(true, forKey: "Viewed")
myProduct.saveInBackground()
} else {
print("it exists")
}
}
}