Delete duplicate object in master data (fast)

I save the objects to the underlying data from the JSON that I get with the loop for(let's say I called this function setup. Since the user can stop this loop, the objects stored in the main data will be partial. The user can restart this function setupby restarting the parsing and procedure to save object data according to the main data.

Now I get duplicated objects in the master data if I restart setup(). The object has an attribute id.

I thought that I could get the first objects that could eventually exist in the main data, store them in an array (native type) and test each new object to add to the main data if it already exists with the same id. The code used is as follows:

if !existingCards.isEmpty {
    for existingCard in existingCards {
        if id == existingCard.id {
           moc.deleteObject(existingCard)
           println("DELETED \(existingCard.name)")
        }
    }
}

...
// "existingCards is the array of object fetched previously.
// Code to save the object to core data.

In fact, the application returns

EXC_BAD_ACCESS (code = 1, address Ox0)

Is there an easier way to achieve my goal or what should I fix to get my code working? I am completely new to fast and I can not understand another solution. The main goal is to remove duplicate baseline data, BTW.

+4
source share
2 answers

Swift 4 code to remove duplicate object:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Card")
        var resultsArr:[Card] = []
        do {
            resultsArr = try (mainManagedObjectContext!.fetch(fetchRequest) as! [Card])
        } catch {
            let fetchError = error as NSError
            print(fetchError)
        }

 if resultsArr.count > 0 {
  for x in resultsArr {
    if x.id == id {
          print("already exist")
          mainManagedObjectContext.deleteObject(x)
        }
      }
   }
+1
source

In the end, I managed to get it to work.

, , moc.deleteObject() , , viewDidLoad().

// DO: - Fetch existing cards
var error: NSError?
var fetchRequest = NSFetchRequest(entityName: "Card")
if let results = moc.executeFetchRequest(fetchRequest, error: &error) as? [Card] {

   if !results.isEmpty {
     for x in results {
        if x.id == id {
          println("already exist")
          moc.deleteObject(x)
        }
     }
   }
} else {
   println(error)
}

existingCards, . - , . - / , .

P.S.: Apple , , Obj-C. , , .

+4

All Articles