2015-10-20 61 views
1

我試圖通過查詢兩個對象用戶和項目來防止重複的項目被複制。如果它們存在,則不要複製,但如果它不存在,則創建它的一個實例。我知道它會一直運行,並根據解析中出現的項目數量做出多個重複項。有誰知道如何防止它重複這些值?如何查詢特定項目的解析並防止重複被保存

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

我不是故意回答我自己的問題,但我明白了。它按計劃正在工作。這是我的代碼。它現在可以工作,但是我再次嘗試了我的早期解決方案,除非事後沒有解決。這對所有人都好嗎?這會讓我頭疼嗎?

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") 
     } 

    } 

} 
0

您可以使用NSSet存儲唯一對象。

+0

我試着做一個NSSet,但它仍然使解析上該項目的副本。 – mn1