我正在使用Swift 3.0中的一个项目,我有一个CoreData
模块,其中有五个属性,类型为String,NSManageObject
名为MP3Details
。它们是持续时间trackID
,trackName
,trackURL
。
要求是,一旦我传递trackID
,我需要检索与该ID相关的元素。例如,一旦我通过trackID
,我就会获得属于该曲目ID的曲目时长trackName
等。
截至目前,我得到的是一个空数组。部分完成的代码,我传递trackID
并获取属于该ID的信息,如下所示。我在这里缺少什么?
我传递trackID
if let arr = StorageManager.getTrackId(playlistName: playlistName) {
for object in arr {
let trackId = object.trackID
print(trackId ?? "ID")
if let detailsArr = StorageManager.getTrackDetails(trackId: trackId) {
print("CoreDataItemArray :", detailsArr)
}
}
方法是否从CoreData请求详细信息
public static func getTrackDetails(trackId:String?) -> [MP3Details]?{
let appDelegate = UIApplication.shared.delegate as! AppDelegate;
let context = appDelegate.persistentContainer.viewContext;
let request = NSFetchRequest<NSFetchRequestResult>(entityName: MP3_DETAILS_ENTITY)
if(trackId != nil){
request.predicate = NSPredicate(format:"trackID = %@", trackId!)
}
request.returnsObjectsAsFaults = false
do{
let results = try context.fetch(request)
print("Result : ",results)
if(results.count > 0 ){
return results as? [MP3Details]
}else{
print("No Mp3 results for the track ID")
}
}catch{
print("Error in fetching items")
}
return nil;
}
答案 0 :(得分:0)
func loadData() - &gt;无效{
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedObjContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
do {
names = try managedObjContext.fetch(fetchRequest)
} catch let error as NSError {
print("Error while fetching the data:: ",error.description)
}
}
@IBAction func addNewName(_ sender: Any) {
let alert = UIAlertController(title: "Add Name", message: "Add new name:", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "Add", style: UIAlertActionStyle.default) { action in
guard let textField = alert.textFields?.first ,
let nameToSave = textField.text else{
return
}
print("nameToSave::: ",nameToSave)
self.save(name:nameToSave)
self.hitListTableView.reloadData()
}
alert.addTextField()
let alertCancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(alertAction)
alert.addAction(alertCancelAction)
self.present(alert, animated: true, completion: nil)
}
func save(name:String) -> Void {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)
let person = NSManagedObject(entity: entity!, insertInto: managedContext)
person.setValue(name, forKey: "name")
do {
try managedContext.save()
names.append(person)
} catch let error as NSError {
print("Error while saving the data: ",error.localizedDescription)
}
}
答案 1 :(得分:0)
尝试用以下语句替换谓词行:
request.predicate = NSPredicate(format:"%K == %@", "trackID", trackId!)