Created
July 11, 2016 18:04
-
-
Save pronebird/2a21b67995daa9c8357d55ea50873947 to your computer and use it in GitHub Desktop.
Sample Core Data Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Playground is where kids play biatch | |
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) | |
city.name = "City \(i)"; | |
try? managedObjectContext.save() | |
} | |
} | |
let fetchRequest = NSFetchRequest(entityName: "City") | |
let countExpr = NSExpressionDescription() | |
countExpr.name = "count" | |
countExpr.expression = NSExpression(format: "count:(name)") | |
countExpr.expressionResultType = .Integer64AttributeType | |
fetchRequest.resultType = .DictionaryResultType | |
fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "name", ascending: true) ] | |
fetchRequest.propertiesToGroupBy = [ cityEntity.propertiesByName["name"]! ] | |
fetchRequest.propertiesToFetch = [ cityEntity.propertiesByName["name"]!, countExpr ] | |
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