ios - 以一个名称将多个对象保存到 coredata
<p><p>我正在 swift 3.0 中开发一个项目,其中我有一个带有多个选择选项的 <code>UITableView</code>(每行都有一个 URL)。因此,在 <code>UITableView</code> 之上,用户可以在 UITextfield 中输入名称。我的要求是,一旦选择了这些行,数据应保存在 <code>Coredata</code> 中键入的名称下。截至目前,数据已保存为单独的元素,因此我无法在其名称下聚类数据。我怎么能做到这一点???。我保存和提取数据的方法如下。</p>
<p>保存</p>
<pre><code>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")
}
}
</code></pre>
<p>获取保存的数据</p>
<pre><code> public static func getPlayList() -> ?{
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! {
let playListDetails:PlayListDetails? = result as? PlayListDetails
print("Title: \(playListDetails?.playlistName)")
}
return results as?
}else{
print("No results")
}
}catch{
print("Error in fetching items")
}
return nil;
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>创建一个字典并使用正确的键将所有字段保存在字典中。然后将dict转换为数据并保存在coreData中
正在保存..</p>
<pre><code>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");
</code></pre>
<p>检索</p>
<p>先从CoreData中获取数据,再转成Dictionary。</p>
<pre><code>let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 以一个名称将多个对象保存到 coredata,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/43840890/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/43840890/
</a>
</p>
页:
[1]