Swift:将 CoreData 获取为数组

Posted

技术标签:

【中文标题】Swift:将 CoreData 获取为数组【英文标题】:Swift: Fetch CoreData as Array 【发布时间】:2014-12-18 21:50:09 【问题描述】:

我想获取 sqlite 表中所有保存的数据。

我目前正在这样做:

 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;

我在 Objective-C 中获取数据没有问题,但在 swift 中我不明白!

数据的保存工作正常。我有两行“名称”和“类别”。如何显示所有保存的数据?

【问题讨论】:

【参考方案1】:

您应该将所有对象从 CoreData 加载到 NSManaged 对象的数组/字典中。

例如:

    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)   

    

【讨论】:

如果获取请求失败,executeFetchRequest() 返回一个 optional,即 nil。如果您强制转换为[Locations],那么应用程序将在这种情况下崩溃。 (比较***.com/a/26459060/1187415.) 你可以考虑typed approach。【参考方案2】:

试试这个:

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


【讨论】:

【参考方案3】:

斯威夫特 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)
    



【讨论】:

所有检索到的 nsmanagedObject 都保留在内存中,即使 viewcontroller 正确 deinit。【参考方案4】:

2020 语法

复制粘贴

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

请注意,core.container.viewContext 是“您的”上下文,通常(但不总是)由core.container.viewContext 提供。 (Example)

关键提示...

在某些情况下:

请务必绝对不要意外使用“错误”上下文。

例如,您正在做一件小事,例如数数或只是抓住所有物品。

这个问题在HERE的大标题下解释了“exerexextreme care...”

【讨论】:

【参考方案5】:

您不必(强制)从 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)   


另一个注意事项:通常您应该以单数形式命名实体,例如“Location”,而不是“Locations”。然后位置数组是位置。 let locations = Array&lt;Location&gt;(location1, location2)

【讨论】:

【参考方案6】:
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
        
    

【讨论】:

我相信这个答案是不小心放在了错误的问题上?

以上是关于Swift:将 CoreData 获取为数组的主要内容,如果未能解决你的问题,请参考以下文章

在 CoreData 中存储和获取字典数组

将数组保存到 CoreData Swift

CoreData 中的 Swift 数组

Swift 从 CoreData 转换为 CoreLocation - 有一些问题

在 CoreData 数据库中存储包含 CGPoints 的数组(Swift)

CoreData Predicate 获取包含数组中任何单词的每个句子