我试图通过查询两个对象(一个用户和一个项目)来防止重复的项目。如果它们存在,则不重复,但如果不存在,则创建一个实例。我知道它一直在运行,并根据解析中存在的项的数量而产生几个重复项。有人知道如何防止它复制这些值吗?
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
}
}
}
})
}发布于 2015-10-20 16:15:03
我不想回答我自己的问题,但我想明白了。它现在正在按计划工作。这是我的密码。它现在起作用了,但我想我以前的解决方案也起作用了,除非后来没有。每个人都觉得这个好看吗?这以后会让我头疼吗?
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")
}
}
}发布于 2015-10-20 05:57:19
您可以使用NSSet存储唯一的对象。
https://stackoverflow.com/questions/33228415
复制相似问题