Search code examples
iossqlitecore-dataswift

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?


Solution

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