I want to fetch all Saved Data in the sqlite table.
I'm currently doing this:
func GetAllData() -> NSArray
{
var error : NSError? = nil;
var request : NSFetchRequest = NSFetchRequest(entityName: "Locations");
let result : [AnyObject] = managedObjectContext!.executeFetchRequest(request, error:&error)!;
var elements : NSMutableArray = NSMutableArray();
for fetchedObject in result
{
elements.addObject(fetchedObject[0]);
}
print(elements);
return elements;
}
I have no problems to fetch Data in Objective-C but in swift I dont get it!
The saving of the data works fine. I have two rows "Name" and "Category". How can I show all saved data?
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)
}
}
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)
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..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With