我正在尝试保存要分析的歌曲信息,但是如果该歌曲已经存在于分析中,我希望我的代码什么也不做。
我在下面尝试过此代码:
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循环更多?以及如何防止解析中出现重复项?
给我任何建议,在obj c或swift中都没关系
我建议在Parse Cloud代码上实现一个简单的beforeSave触发器,以检查新的输入歌曲是否已经存在(基本上,您将使一个或多个字段唯一。例如:
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(); } }); });
希望能帮助到你。