Swift: Fetch CoreData as Array
You should load all your Objects from CoreData into an Array/Dict of NSManaged Objects.
For Example:
var locations = [Locations]() // Where Locations = your NSManaged Class
var fetchRequest = NSFetchRequest(entityName: "Locations")
locations = context.executeFetchRequest(fetchRequest, error: nil) as [Locations]
// Then you can use your properties.
for location in locations {
print(location.name)
}
Try this:
let fetchRequest = NSFetchRequest(entityName: "Locations")
do {
let results = try managedObjectContext.executeFetchRequest(fetchRequest)
let locations = results as! [Locations]
for location in locations {
print(location)
}
} catch let error as NSError {
print("Could not fetch \(error)")
}
Swift 3
func fetchData(){
onlyDateArr.removeAll()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "PhotoData")
do {
let results = try context.fetch(fetchRequest)
let dateCreated = results as! [PhotoData]
for _datecreated in dateCreated {
print(_datecreated.dateCreation!)
onlyDateArr.append(_datecreated)
}
}catch let err as NSError {
print(err.debugDescription)
}
}
2020 syntax
to copy and paste
func grabAllPersons() {
var pp: [CD_Person] = []
do {
let r = NSFetchRequest<NSFetchRequestResult>(entityName: "CD_Person")
let f = try core.container.viewContext.fetch(r)
pp = f as! [CD_Person]
} catch let error as NSError {
print("woe grabAllPersons \(error)")
}
for p: CD_Person in pp {
print(" >> \(p.firstName)")
}
}
Note that core.container.viewContext
is "your" context, often (but not always) the one supplied by core.container.viewContext
. (Example)
Critical tip...
In some cases:
it is ABSOLUTELY important that you do not accidentally use the "wrong" context.
For example, you are doing a minor incidental issue, such as counting or just grabbing all the items.
This issue is explained HERE under the large heading "exercise extreme caution..."