OGeek|极客世界-中国程序员成长平台

标题: ios - 以一个名称将多个对象保存到 coredata [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:37
标题: ios - 以一个名称将多个对象保存到 coredata

我正在 swift 3.0 中开发一个项目,其中我有一个带有多个选择选项的 UITableView(每行都有一个 URL)。因此,在 UITableView 之上,用户可以在 UITextfield 中输入名称。我的要求是,一旦选择了这些行,数据应保存在 Coredata 中键入的名称下。截至目前,数据已保存为单独的元素,因此我无法在其名称下聚类数据。我怎么能做到这一点???。我保存和提取数据的方法如下。

保存

public static func savePlaylistDetails(audio:AudioDetails, playListName: String) {

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)


    newPlaylist.setValue(playListName, forKey:"playlistName");
    newPlaylist.setValue(audio.mediaId, forKey:"trackID");

    do{
        try context.save();
        print("Saved.....")
    }
    catch{
        print("There was an error")
    }
}

获取保存的数据

    public static func getPlayList() -> [PlayListDetails]?{
    let appDelegate = UIApplication.shared.delegate as! AppDelegate;
    let context = appDelegate.persistentContainer.viewContext;

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: PlayList_DETAILS_ENTITY)
    request.returnsObjectsAsFaults = false

    do{
        let results = try context.fetch(request)
        if(results.count > 0 ){
            for result in results as! [NSManagedObject]{
                let playListDetailslayListDetails? = result as? PlayListDetails
                print("Title: \(playListDetails?.playlistName)")


            }
            return results as? [PlayListDetails]
        }else{
            print("No results")
        }

    }catch{
        print("Error in fetching items")
    }
    return nil;
}



Best Answer-推荐答案


创建一个字典并使用正确的键将所有字段保存在字典中。然后将dict转换为数据并保存在coreData中 正在保存..

let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
 let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let newPlaylist = NSEntityDescription.insertNewObject(forEntityName: PlayList_DETAILS_ENTITY, into: context)


    newPlaylist.setValue(data , forKey:"playlistData");

检索

先从CoreData中获取数据,再转成Dictionary。

let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

关于ios - 以一个名称将多个对象保存到 coredata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43840890/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4