21

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?

6 Answers 6

35

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)   

    }
Sign up to request clarification or add additional context in comments.

2 Comments

executeFetchRequest() returns an optional which is nil if the fetch request fails. If you forcefully cast to [Locations] then the app will crash in that case. (Compare stackoverflow.com/a/26459060/1187415.)
You might consider a typed approach.
12

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


}

1 Comment

All retrived nsmanagedObject stays in memory even if the viewcontroller deinit properly.
12

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

Comments

6

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

Comments

0

You don't have to (force) cast any result from NSFetchRequest:

var locations  = [Locations]()
var fetchRequest = NSFetchRequest<Locations>(entityName: "Locations") //Note the <Locations> makes the NSFetchRequestResult to an array of Locations 
locations = context.executeFetchRequest(fetchRequest, error: nil)
 
for location in locations {
    print(location.name)   
}

Another note: Usually you should name your entities in singular like "Location", not "Locations". And then an array of Location are locations. let locations = Array<Location>(location1, location2)

Comments

-1
import UIKit
import CoreData
class CoreDataHandler: NSObject {

    private class func getContext() -> NSManagedObjectContext
    {
        let delegate = UIApplication.shared.delegate as? AppDelegate

        return (delegate?.persistentContainer.viewContext)!
    }


    class func saveObeject (name:String,roll:String,college:String)
    {
        let context =  getContext()
        let entity = NSEntityDescription.entity(forEntityName: "CountryInfo", in: context)

        let manageObjet = NSManagedObject(entity: entity!, insertInto: context)

        manageObjet.setValue(name, forKey: "name")
        manageObjet.setValue(roll, forKey: "roll")
        manageObjet.setValue(college, forKey: "college")


        do
        {
            try context.save()
        }catch
        {
            print("unable to save data")
        }
    }

    class func getCountryDetail(name:String) ->Array<Any>?
    {

        // return "http://1.bp.blogspot.com/-J9emWhBZ_OM/TtQgVQmBHRI/AAAAAAAAD2w/j7JJMRMiuAU/s1600/Al_Ain_FC.png"
        let contecxt = getContext()
        let fetchRequest:NSFetchRequest<CountryInfo> = CountryInfo.fetchRequest()

        var user:[CountryInfo] = []
        let predicate = NSPredicate(format: "name LIKE[cd] %@",name)
        fetchRequest.predicate = predicate
        do{
            user =  try contecxt.fetch(fetchRequest)
            let ClubInfoBO = user
            print(ClubInfoBO)
            return (ClubInfoBO) as? Array<Any>
        }catch
        {
            return nil

        }

    }


    class func deleteObject(user:CountryInfo) ->Bool{
        let context = getContext()
        context.delete(user)
        do
        {
            try context.save()
            return true
        }catch{
            return false
        }
    }

    //Clean delete

    class func cleanDelete () ->Bool
    {
        let context = getContext()
        let delete = NSBatchDeleteRequest(fetchRequest: CountryInfo.fetchRequest())

        do{
            try context.execute(delete)
            return true
        }catch
        {
            return false
        }
    }
}

1 Comment

i believe this answer was accidentally placed on the wrong question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.