我正在研究一个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 playListDetails:PlayListDetails? = result as? PlayListDetails
print("Title: (playListDetails?.playlistName)")
}
return results as? [PlayListDetails]
}else{
print("No results")
}
}catch{
print("Error in fetching items")
}
return nil;
}
创建一个字典,并使用适当的键保存在字典中的所有字段。然后将DICE转换为数据并将其保存在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获取数据,然后再次将其转换为字典。
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)