2014-10-23 17 views
6

voglio prendere tutti i dati salvati nella tabella SQLite.Swift: Fetch CoreData come Array

Attualmente sto facendo questo:

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

non ho problemi a recuperare i dati in Objective-C, ma in rapida io non farlo!

Il salvataggio dei dati funziona bene. Ho due righe "Nome" e "Categoria". Come posso mostrare tutti i dati salvati?

risposta

21

è necessario caricare tutti i vostri oggetti da CoreData in un array/Dict di NSManaged oggetti.

Per esempio:

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) 

} 
+0

SI! Grazie amico! – TdoubleG

+4

'executeFetchRequest()' restituisce un * facoltativo * che è 'quelle negative se la richiesta di recupero non riesce. Se si esegue il cast forzato su '[Locations]' allora l'app si bloccherà in quel caso. (Confronta http://stackoverflow.com/a/26459060/1187415.) –

+0

Si potrebbe prendere in considerazione un [approccio digitato] (http://stackoverflow.com/a/27365921/482529). –

5

Prova questo:

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

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


} 
+0

buono, molto Aiuto ful !!! –