Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Fetch CoreData as Array

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?

like image 386
TdoubleG Avatar asked Oct 23 '14 08:10

TdoubleG


4 Answers

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)   

    }
like image 51
derdida Avatar answered Oct 10 '22 15:10

derdida


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)")
}

like image 21
Vikram Biwal Avatar answered Oct 10 '22 16:10

Vikram Biwal


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)
    }


}
like image 10
Abdul Karim Avatar answered Oct 10 '22 17:10

Abdul Karim


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..."

like image 6
Fattie Avatar answered Oct 10 '22 17:10

Fattie