web-dev-qa-db-fra.com

Swift: Récupérer les données de base sous forme de tableau

Je veux récupérer toutes les données enregistrées dans la table sqlite.

Je suis en train de faire ceci:

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

Je n'ai aucun problème pour récupérer des données dans Objective-C mais dans Swift, je ne les ai pas!

La sauvegarde des données fonctionne bien. J'ai deux lignes "Nom" et "Catégorie". Comment puis-je afficher toutes les données sauvegardées?

12
TdoubleG

Vous devez charger tous vos objets de CoreData dans un tableau/Dict of NSManaged Objects.

Par exemple:

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)   

}
29
derdida

Essaye ça:

let fetchRequest = NSFetchRequest(entityName: "Locations")

 do {
     let results = try managedObjectContext.executeFetchRequest(fetchRequest)
     let  Locations = results as! [Locations]

     for location in Locations {
        println(location)   
     }
    } catch let error as NSError {
       print("Could not fetch \(error)”)
 }
7
CrazyVK

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


}
6
Abdul Karim
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
        }
    }
}
0
user9476144