我创建了一个函数,通过点击 UI 上的收藏按钮返回解析中创建“收藏”对象:
//MARK: Create the favorite object
func createFavorite(){
let currentUser = PFUser.currentUser()
let currentBook = PFObject(withoutDataWithClassName: "Books", objectId: objectIdSelected)
let favorite = PFObject(className:"Favorites")
favorite["user"] = currentUser
favorite["books"] = currentBook
favorite.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// success
} else {
// There was a problem, check error.description
}
}
}
现在我正在尝试创建一个查询,使用以下逻辑检查是否存在具有这些确切属性的收藏夹对象,我已将其放置在显示特定书籍的 VC 的 viewDidLoad 中:
//MARK: Check if there is a favorite object available
func isFavoritedByUser(){
let currentUser = PFUser.currentUser()
let currentBook = PFObject(withoutDataWithClassName: "Books", objectId: objectIdSelected)
let query = PFQuery(className:"Favorites")
query.whereKey("user", equalTo: currentUser!)
query.whereKey("books", equalTo: currentBook)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if objects != nil {
print("this book was favorited by this user")
} else if objects == nil {
print("this book WAS NOT favorited by this user")
} else if error == nil {
// succeed
} else if error != nil {
// There was a problem, check error.description
}
}
}
但是,即使我的解析类中不存在具有这些属性的最喜欢的对象,它仍然会打印“这本书被该用户最喜欢”。我在这里缺少什么?
最佳答案
现有的列表不是证据。这只是证明没有观察到某种错误。
你应该首先检查没有错误,然后你应该检查对象列表中是否有一个项目。
如果列表中有多个项目,那么您正在创建重复项,您应该解决这个问题...
关于ios - 如何使用 swift 正确检查解析中的现有对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35001708/