检查核心数据数据库中保存的 ID,并在 Swift 3 中显示/隐藏"添加到收藏夹"按钮



我有一个配置文件视图控制器(VC1(,在这个VC1上,我有一个按钮,上面写着"添加到收藏夹"。当我点击此按钮时,我可以将此详细信息(ID和配置文件名称(保存在Core Data数据库中,并能够在我的收藏夹视图控制器(VC2(的表列表视图中查看此数据。现在,当我转到VC2时,我可以看到表格列表中的所有收藏夹,当我单击其中一条记录时,它将显示该配置文件的详细信息。

但现在的问题是,我在这里的按钮"添加到收藏夹",我需要将其更改为"从收藏夹中删除">,因为此配置文件已被标记为收藏夹。

我能够理解这个概念,obj ID 需要在数据库中检查,如果有匹配项,那么 Button.setTitle 将更改并执行所需的功能。但我无法正确弄清楚这一点。

感谢您的时间,非常感谢!!

我保存数据的代码

@IBOutlet weak var fav_remove_fav_button_label: UIButton!

@IBAction func saveFav(_ sender: Any) {
var proID = saved_id
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = FavProfile(context: context) // Link Task & Context
task.busName = bussinessName
task.profileID = Int32(id!)!
print ("saved id is: - (task.profileID)")
print ("saved profile name is: - (task.busName)")
fav_remove_fav_button_label.setTitle("Remove From Favourite", for: .normal)
// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
// let _ = navigationController?.popViewController(animated: true)
let alert = UIAlertController(title: "Alert", message: "Added to your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

}

我获取和检查数据的函数

func isExist(id: Int) -> Bool {
var error: NSError?
var moc: NSManagedObjectContext!
var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
if let results = try! moc.fetch(fetchRequest) as? [FavProfile] {
if !results.isEmpty {
for x in results {
if x.profileID  == Int32(id) {
print("already exist")
moc.delete(x)
}
}
}
} else {
print(error)
}
return false
}

试试这个 ->

func isExist(id: Int) -> Bool {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var error: Error? = nil
let fetch = NSFetchRequest<NSFetchRequestResult>()
let entityDescription = NSEntityDescription.entity(forEntityName: "FavProfile", in: context)
fetch.entity = entityDescription
as? NSEntityDescription!
NSEntityDescription()
fetch.predicate = NSPredicate(format: "profileID == %d", id)
let fetchedObjects: [Any]? = try? context.fetch(fetch)
if error != nil {
return false
}
else {
if (fetchedObjects?.count)! > 0 {
print("fetchedObjects--->found");
return true
}
else {
print("fetchedObjects--->nil");
return false
}
}
}

override func viewDidLoad() {
super.viewDidLoad()
//  favButtonLabel()
//   isExist(id: 182397)
let FavCheck: Bool = isExist(id:182397)
if FavCheck == true {
print("favourite--->");
}
}

最新更新