2017-06-08 82 views
0

我有一个nstableview,我填写核心数据的数据。核心数据nstableview搜索栏

NSManagedObject

import Foundation 
import CoreData 

@objc(Person) 
public class Person: NSManagedObject { 
    @NSManaged public var firstName: String 
    @NSManaged public var secondName: String 
} 

的RequestData

func requestData() { 
     let appdelegate = NSApplication.shared().delegate as! AppDelegate 
     let context = appdelegate.persistentContainer.viewContext 
     let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") 

     do { 
      person = try context.fetch(request) as! [Person] 
      tableViewn.reloadData() 
     } catch { } 
    } 

我也有我的tableView的自定义单元格视图。 我填写的数据是这样的:

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { 

     let view = tableView.make(withIdentifier: "Cell", owner: self) as? CustomCell 

     view?.txtfirstName.stringValue = person.firstName 
     view?.txtsecondName.stringValue = person.secondName 
     return view 
} 

现在我想实现与第一或第二名搜索搜索栏(我已经在我的视图控制器)。

但我不知道如何我可以实现这一点。

+0

你是如何实现搜索栏的?当你尝试什么? – Willeke

+0

如果使用'NSSearchField'和'NSArrayController',则将搜索字段的谓词绑定到数组控制器的过滤器谓词。不需要编码。 – Willeke

回答

0
  • 设置NSSearchField的委托目标类
  • 实施controlTextDidChange

    override func controlTextDidChange(_ notification: Notification) { 
        if let field = notification.object as? NSSearchField { 
         let query = field.stringValue 
         let predicate : NSPredicate? 
         if query.isEmpty { 
          predicate = nil 
         } else { 
          predicate = NSPredicate(format: "firstName contains[cd] %@ OR lastName contains[cd] %@", query, query) 
         } 
         requestData(with: predicate) 
        } else { 
         super.controlTextDidChange(notification) 
        } 
    } 
    
  • 变化requestData

    func requestData(with predicate : NSPredicate? = nil) { 
        let appdelegate = NSApplication.shared().delegate as! AppDelegate 
        let context = appdelegate.persistentContainer.viewContext 
        let request = NSFetchRequest<Person>(entityName: "Person") 
        request.predicate = predicate 
    
        do { 
         person = try context.fetch(request) 
         tableViewn.reloadData() 
        } catch { } 
    } 
    

旁注:

如果您使用的是NSManagedObject子类,请创建更具体的获取请求NSFetchRequest<Person>(entityName...而不是NSFetchRequest<NSFetchRequestResult>(entityName...,这可避免获取行中的类型转换。

+0

完美!非常感谢 :) – Ghost108