2014-10-23 23 views
6

Tôi muốn tìm nạp tất cả Dữ liệu đã lưu trong bảng sqlite.Swift: Lấy CoreData làm Array

tôi đang làm điều này:

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

Tôi không có vấn đề để lấy dữ liệu trong Objective-C nhưng trong nhanh chóng Tôi không nhận được nó!

Việc lưu dữ liệu hoạt động tốt. Tôi có hai hàng "Tên" và "Danh mục". Làm thế nào tôi có thể hiển thị tất cả dữ liệu đã lưu?

Trả lời

21

Bạn nên tải tất cả các đối tượng của bạn từ CoreData vào một mảng/Dict của NSManaged Objects.

Ví dụ:

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

YES! Cảm ơn anh bạn! – TdoubleG

+4

'executeFetchRequest()' trả về một * tùy chọn * là 'nil' nếu yêu cầu tìm nạp không thành công. Nếu bạn ép mạnh vào '[Locations] 'thì ứng dụng sẽ gặp sự cố trong trường hợp đó. (So ​​sánh http://stackoverflow.com/a/26459060/1187415.) –

+0

Bạn có thể xem xét [cách tiếp cận đã nhập] (http://stackoverflow.com/a/27365921/482529). –

5

Hãy thử điều này:

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

Tốt, Rất Trợ giúp ful !!! –

Các vấn đề liên quan