如何防止重复输入解析?

我试图将歌曲信息保存到解析中,但如果该歌曲已经存在于解析中,我希望我的代码什么都不做。

我在下面尝试过以下代码:

var Music = PFObject(className:"Musics") var query = PFQuery(className:"Musics") query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil { // The find succeeded. println("Successfully retrieved \(objects!.count) scores.") // Do something with the found objects if let objects = objects as? [PFObject] { for object in objects { var songTitle = object.objectForKey("songTitle") as? String if songTitle != title { Music["createdBy"] = PFUser.currentUser() Music["songTitle"] = title Music["albumCover"] = imageFile Music["songArtist"] = artist Music.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in if (success) { println("succeed") } else { // There was a problem, check error.description println("error jeh") } } }else{ println("song already exist") } } } } else { // Log details of the failure println("Error: \(error!) \(error!.userInfo!)") } } 

上面的代码在日志上给出了以下结果:

成功检索到4个分数。 歌已经存在已成功检索到4个分数。 歌已经存在已成功检索到4个分数。 歌已经存在已成功检索到4个分数。 歌曲已经存在成功成功成功成功成功成功成功成功成功

为什么我的for循环,循环比Objects.count更多? 以及如何防止在解析时出现重复输入?

给我任何建议,无论是对象还是快速

我建议在Parse Cloud代码上实现一个简单的beforeSave触发器,以检查新的条目歌曲是否已经存在(基本上你将创建一个或多个字段uniques。例如:

 Parse.Cloud.beforeSave("Musics", function(request, response) { var newEntrySong = request.object; var querySongs = new Parse.Query("Musics"); querySongs.equalTo("title", newEntrySong.get("title")); querySongs.equalTo("description", newEntrySong.get("description")); // this could be a sort of signature for your song, to make more unique (skipping spaces and new lines for example) querySongs.equalTo("md5Title", newEntrySong.get("md5Title")); querySongs.first({ success: function(temp) { response.error({errorCode:123,errorMsg:"Song already exist!"}); }, error: function(error) { response.success(); } }); }); 

希望能帮助到你。

Interesting Posts