![](/img/trans.png)
[英]How to specify Destination for Core Data fetchRequest programmatically?
[英]How to use predicates with fetchRequest in Core Data
我將聯系人標識符從聯系人表視圖控制器傳遞到另一個位置表視圖控制器。 所以我定義了一個委托 ContactSelectionDelegate 並在 Location tableview 控制器中實現方法 userSelectedContact 並獲得 contactIdentifierString
我正在搜索數據庫以查找 contactIdentifierString 的匹配項並查找另一個屬性提供程序名稱的值。 這涉及搜索整個數據庫。 是否有通過將謂詞分配給上下文 fetchRequest 的更快方法。 我認為這會更快,代碼行更少。
有人可以建議如何將謂詞與 contact fetchRequest 一起使用嗎?
ContactTableViewController 代碼:
protocol ContactSelectionDelegate{
func userSelectedContact(contactIdentifier:NSString)
}
class ContactTableViewController: UITableViewController {
var delegate:ContactSelectionDelegate? = nil
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if (delegate != nil){
let contactDict:NSDictionary = allContacts.object(at: indexPath.row) as! NSDictionary
let identifier = contactDict.object(forKey: "uniqueId")
delegate!.userSelectedContact(contactIdentifier: identifier as! NSString)
self.navigationController!.popViewController(animated: true)
}
}
}
LocationTableViewController 代碼:
class LocationTableViewController: UITableViewController, ContactSelectionDelegate, CLLocationManagerDelegate {
var contactIdentifierString:NSString = NSString()
func userSelectedContact(contactIdentifier: NSString) {
var fetchedResults: [Contact] = []
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
fetchedResults = try context.fetch(Contact.fetchRequest())
}
catch {
print ("fetch task failed")
}
if fetchedResults.count > 0 {
for contact in fetchedResults{
let aContact:Contact = contact
if (aContact.uniqueId! == contactIdentifierString as String) {
providerName.text = aContact.providerName
}
else {
continue
}
}
}
}
首先擺脫所有NSString
和NSDictionary
出現。 這是斯威夫特!。 使用 Swift 原生結構String
和Dictionary
。
其次,始終將所有好的代碼放在do - catch
塊的do
范圍內。
CoreData 謂詞有一個簡單的格式attribute == value
,它與aContact.uniqueId! == contactIdentifierString
非常相似aContact.uniqueId! == contactIdentifierString
aContact.uniqueId! == contactIdentifierString
:
var contactIdentifierString = ""
func userSelectedContact(contactIdentifier: String) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do {
let fetchRequest : NSFetchRequest<Contact> = Contact.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "uniqueId == %@", contactIdentifier)
let fetchedResults = try context.fetch(fetchRequest)
if let aContact = fetchedResults.first {
providerName.text = aContact.providerName
}
}
catch {
print ("fetch task failed", error)
}
}
代碼假設有一個NSManagedObject
子類Contact
包含
@nonobjc public class func fetchRequest() -> NSFetchRequest<Contact> {
return NSFetchRequest<Contact>(entityName: "Contact")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.