Swift4中如何使用CoreData保存数据且避免重复写入值?
Fixing Duplicate Data in CoreData for Swift 4
Hey there! Let's tackle that duplicate data issue you're facing when saving products with CoreData. The core solution here is simple: check if the product already exists in your store before creating a new managed object.
Here's how to modify your CoreDataHandler class to implement this logic:
Updated Code with Duplicate Prevention
import UIKit import CoreData class CoreDataHandler: NSObject { private class func getContext() -> NSManagedObjectContext { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext } class func saveProduct(p : [String: Any]) { let context = getContext() // First, grab the unique identifier for your product (adjust this to your actual unique field) guard let productId = p["productId"] as? String else { print("Error: Missing required unique product ID") return } // Create a fetch request to search for an existing product with the same ID let fetchRequest: NSFetchRequest<Product> = Product.fetchRequest() fetchRequest.predicate = NSPredicate(format: "productId == %@", productId) do { let existingProducts = try context.fetch(fetchRequest) // Only create a new product if no match is found if existingProducts.isEmpty { let entity = NSEntityDescription.entity(forEntityName: "Product", in: context) let newProduct = NSManagedObject(entity: entity!, insertInto: context) // Populate your product properties (fill in the rest of your original logic here) newProduct.setValue(productId, forKey: "productId") newProduct.setValue(p["name"], forKey: "name") newProduct.setValue(p["price"], forKey: "price") // Add any other product attributes you need to save try context.save() print("Product saved successfully!") } else { print("Product with ID \(productId) already exists — skipping save.") // Optional: If you want to update existing product data instead of skipping, uncomment below // let existingProduct = existingProducts.first! // existingProduct.setValue(p["name"], forKey: "name") // try context.save() // print("Existing product updated!") } } catch let error as NSError { print("Failed to fetch or save product: \(error.localizedDescription), \(error.userInfo)") } } }
Key Details to Note
- Unique Identifier: I used
productIdas the unique field here, but you should replace this with whatever unique attribute yourProductentity uses (like a SKU or UUID). Make sure this field exists in your CoreData model file (xcdatamodeld). - Add a Unique Constraint (Extra Safety): For an extra layer of protection, open your CoreData model, select the
productIdfield, and in the Data Model Inspector, check the "Unique" box. This will make CoreData throw an error if you accidentally try to insert a duplicate, even if your code misses a check. - Use Generated Subclasses: For cleaner, safer code, generate an
NSManagedObjectsubclass for yourProductentity (go toEditor > Create NSManagedObject Subclass...in Xcode). This lets you use dot syntax for properties (e.g.,newProduct.productId = productId) instead ofsetValue, avoiding typos with string keys.
内容的提问来源于stack exchange,提问作者Augusto
相关产品推荐
相关产品推荐

