Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pronebird/cca9777af004e9c91f9cd36c23cc821c to your computer and use it in GitHub Desktop.
Save pronebird/cca9777af004e9c91f9cd36c23cc821c to your computer and use it in GitHub Desktop.
Fetch duplicate records with CoreData
// Playground is where kids play
import CoreData
@objc(City)
class City: NSManagedObject {
@NSManaged var name: String
}
var cityEntity = NSEntityDescription()
cityEntity.name = "City"
cityEntity.managedObjectClassName = "City"
var nameAttribute = NSAttributeDescription()
nameAttribute.name = "name"
nameAttribute.attributeType = NSAttributeType.StringAttributeType
nameAttribute.optional = false
nameAttribute.indexed = true
cityEntity.properties = [nameAttribute]
var model = NSManagedObjectModel()
model.entities = [cityEntity]
var persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
let url = NSURL(fileURLWithPath: "database.sqlite")
// destroy store on each run
try persistentStoreCoordinator.destroyPersistentStoreAtURL(url, withType: NSSQLiteStoreType, options: nil)
do {
try persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
}
catch {
print("error creating psc: \(error)")
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
for i in 0 ..< 5 {
for j in 0 ..< 5 {
let city = City(entity: cityEntity, insertIntoManagedObjectContext: managedObjectContext)
if i == 4 && j > 0 {
continue
}
city.name = "City \(i)"
try? managedObjectContext.save()
}
}
let fetchRequest = NSFetchRequest(entityName: "City")
let nameExpr = NSExpression(forKeyPath: "name")
let countExpr = NSExpressionDescription()
let countVariableExpr = NSExpression(forVariable: "count")
countExpr.name = "count"
countExpr.expression = NSExpression(forFunction: "count:", arguments: [ nameExpr ])
countExpr.expressionResultType = .Integer64AttributeType
fetchRequest.resultType = .DictionaryResultType
fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "name", ascending: true) ]
fetchRequest.propertiesToGroupBy = [ cityEntity.propertiesByName["name"]! ]
fetchRequest.propertiesToFetch = [ cityEntity.propertiesByName["name"]!, countExpr ]
fetchRequest.havingPredicate = NSPredicate(format: "%@ > 1", countVariableExpr)
let results = try managedObjectContext.executeFetchRequest(fetchRequest)
print("\(results)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment