2015-06-03 28 views
0

我一直無法弄清楚如何在Swift中做以下工作並尋找指針。如何使用sectionNameKeyPath將組表tableView數據(斯威夫特)

我從Core Data中提取字符串值並在UITableView中顯示它們...這是工作並顯示所有條目。我現在要「組」這些值的創建日期(也存儲在覈心數據),但我有一個很難實現這組頭......這是我有:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var sound = self.sounds[indexPath.row] 
    var cell = UITableViewCell() 

    // Convert Date to String 
    var formatter: NSDateFormatter = NSDateFormatter() 
    formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss" 
    let dateTimePrefix: String = formatter.stringFromDate(sound.dateSaved) 
    // Display the following in each rows 
    cell.textLabel!.text = sound.name + " Saved: " + dateTimePrefix 

    return cell 
} 

有人能指出我正確的方向如何實現'頭'?我已將Main.storyboard設置中的tableView作爲樣式「分組」。

---更新

感謝下面的反應,但不幸的是,這些例子中的OBJ-C,我拍攝的快捷。

擴大,我有以下從核心數據檢索數據並顯示所有的UITableView:

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.tableView.dataSource = self 
    self.tableView.delegate = self 
} 

override func viewWillAppear(animated: Bool) { 
    super.viewWillAppear(animated) 
    var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext! 
    var request = NSFetchRequest(entityName: "Sound") 
    self.sounds = context.executeFetchRequest(request, error: nil)! as [Sound] 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return self.sounds.count 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell") 
    var sound = self.sounds[indexPath.row] 

    // Convert Date to String 
    var formatter: NSDateFormatter = NSDateFormatter() 
    formatter.dateFormat = "yyyy-MM-dd @ HH:mm:ss" 
    let dateTimePrefix: String = formatter.stringFromDate(sound.dateSaved) 
    // Display the following in each rows 
    cell.textLabel!.text = sound.name // Sound Name 
    // Display the following as each subtitles 
    cell.detailTextLabel!.text = dateTimePrefix // Sound Duration (Currently 'date') 

    return cell 
} 

有人能指出我在正確的方向,我怎麼去「分組」分別由一個月使用sectionNameKeyPath的'月'標題,我相信?具體來說,需要修改哪一段代碼才能將列表拆分爲「部分」。

+0

使用NSFetchedResultsController來切斷tableView,這是實現它的首選方法。 – Sandeep

回答

0

這裏有一些指針:

  1. 您需要使用NSFetchedResultsController( 「FRC」) - 檢查出documentation here。您將看到您在初始化FRC時指定sectionNameKeyPath

  2. 有一些樣板代碼用於使用FRC更新tableView。瞭解FRC的最簡單方法是觀察FRC的工作原理,使用Apple的主/從應用程序模板創建項目,確保選擇「使用核心數據」選項。在該項目中與它一起玩,看看它是如何工作的,然後剪切/粘貼到你自己的項目中。

  3. 對於您的情況,您希望將month(和推測爲year?)作爲節名稱。有幾種方法可以做到這一點,但最簡單的方法是在Sound類中創建一個函數(例如sectionIdentifier),該函數返回一個字符串,其段名稱以您想要的格式從dateSaved派生。然後在初始化FRC時指定sectionNameKeyPath:sectionIdentifier