Last active
November 17, 2015 17:41
-
-
Save tomkowz/56ddb30fe8bb8b04f558 to your computer and use it in GitHub Desktop.
Test of searching for not saved data in core data
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
import UIKit | |
import CoreData | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
populateDatabase() | |
} | |
var context: NSManagedObjectContext { | |
return (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext | |
} | |
func populateDatabase() { | |
let names = ["John", "Jenny", "Sam", "Alicia", "Maggie", "Jane"] | |
let ages = [21, 23, 22, 24, 19, 22, 21, 25] | |
for (var idx = 0; idx < names.count; idx++) { | |
let entity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: context) as! Person | |
entity.name = names[idx] | |
entity.age = ages[idx] | |
searchFor(entity.name!) | |
} | |
} | |
func searchFor(name: String) { | |
let fetchRequest = NSFetchRequest(entityName: "Person") | |
fetchRequest.predicate = NSPredicate(format: "name == %@", name) | |
let objects = try! context.executeFetchRequest(fetchRequest) | |
print("results for searching for name [\(name)] = \(objects.first?.objectID)") | |
} | |
} | |
// Output | |
results for searching for name [John] = Optional(0x79f73540 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD292>) | |
results for searching for name [Jenny] = Optional(0x7a161300 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD293>) | |
results for searching for name [Sam] = Optional(0x7a1627a0 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD294>) | |
results for searching for name [Alicia] = Optional(0x7a164040 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD295>) | |
results for searching for name [Maggie] = Optional(0x7a166130 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD296>) | |
results for searching for name [Jane] = Optional(0x7a1640e0 <x-coredata:///Person/tA9493D02-FF5D-4EF5-9BDF-A857487ECD297>) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment