Is there any way we can restrict duplicate entries in core data?

前端 未结 5 1403
温柔的废话
温柔的废话 2021-02-03 14:30

I have been trying to add objects in core data. So, i want that it should not allow duplicate entries in core data store. How to do that? This is my code related to save data.

5条回答
  •  轮回少年
    2021-02-03 14:54

    I think the best approach would be to call the countForFetchRequest method using a predicate to evaluate whether your store has a matching object. Since this type of request does not pull back any objects it should be more performant than other solutions. Here is a Swift 2.0 implementation added to a NSManagedObject subclass.

      func tokenExists (aToken:String) -> Bool {
            let request: NSFetchRequest = NSFetchRequest(entityName: self.className!)
    
            let predicate = NSPredicate(format: "token == %@", argumentArray: [aToken])
    
            request.predicate = predicate
    
            let error: NSErrorPointer = nil
    
            let count = self.managedObjectContext!.countForFetchRequest(request, error: error)
    
            if count == NSNotFound {
                return false
            }
            return true
        }
    

    NB - (One could substitute any equality criteria you like for the predicate but keep in mind that if possible you should use a numerical identifier if one is available ~ for best performance)

    Usage:

    One might then use the function above during the insertion:

    func insertToken (value:String) {
    
            if  !tokenExists(value) {
                self.token = value
                saveState()
            }
    
        }
    

提交回复
热议问题