Swift4でFetchedResultsControllerを使用してDateSectionTitlesを取得する方法

オサマネーム

FRCを使用していて、日付(DD MMMM)に従ってデータをグループ化するセクションを作成したいと思います。各タスクには日付があり、その日付を使用してセクションヘッダーのタイトルにフォーマットしています。

私は、Objective Cで提供されているAppleのサンプルコードを使用して、それをswiftに変換しています。コードは次のとおりです。

import UIKit
import CoreData

class completedNotes: NSManagedObject
{
    @NSManaged var cNote: String
    @NSManaged var cPriorityColor: UIColor
    @NSManaged var cDate: Date

}


extension completedNotes {
var sectionIdentifier : String? {
    // Create and cache the section identifier on demand.

    self.willAccessValue(forKey: "sectionIdentifier")
    var tmp = self.primitiveValue(forKey: "sectionIdentifier") as? String
    self.didAccessValue(forKey: "sectionIdentifier")

    if tmp == nil {
        if let timeStamp = self.value(forKey: "cDate") as? NSDate {
            /*
             Sections are organized by month and year. Create the section
             identifier as a string representing the number (year * 1000) + month;
             this way they will be correctly ordered chronologically regardless
             of the actual name of the month.
             */
            let calendar  = NSCalendar.current

            let components = calendar.dateComponents([.year, .month,], from: timeStamp as Date)
            tmp = String(format: "%ld", components.year! * 1000 + components.month!)
            self.setPrimitiveValue(tmp, forKey: "sectionIdentifier")
        }
    }
    return tmp
}
}

上記のコードは、一時プロパティsectionIdentifierを作成しているNSManagedObjectにあります。NSManagedObjectであるcDateの値を取ります。

その後、 titlesforheaderinSection

 func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    struct Formatter {
        static let formatter : DateFormatter = {
            let fmt = DateFormatter()
            let dateFormat = DateFormatter.dateFormat(fromTemplate: "MMMM yyyy", options: 0,
                                                      locale: NSLocale.current)
            fmt.dateFormat = dateFormat
            return fmt
        }()
    }

    if let theSection = fetchedResultsController1.sections?[section] as? NSFetchedResultsSectionInfo,
        let numericSection = Int(theSection.name) {
        var components = DateComponents()
        components.year = numericSection / 1000
        components.month = numericSection % 1000
        if let date = Calendar.current.date(from: components) {
            let titleString = Formatter.formatter.string(from: date)
            return titleString
        }
    }
    return nil

}

これは、他のテーブルビュー関数に使用しているコードです。

func numberOfSections(in tableView: UITableView) -> Int {
    return (fetchedResultsController1.sections?.count)!
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return fetchedResultsController1.sections![section].numberOfObjects
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellid, for: indexPath) as! TasksTableViewCell
    cell.selectionStyle = .none

    cell.textview.text = fetchedResultsController1.object(at: indexPath).cNote
    cell.priorityline.backgroundColor = fetchedResultsController1.object(at: indexPath).cPriorityColor

    return cell
}

これはNSFetchedResultsControllerです。

let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.moContext1, sectionNameKeyPath: "sectionIdentifier", cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController as? NSFetchedResultsController<completedNotes>

テーブルビューにセクションを表示できないのはなぜですか?また、最後のテーブルビューセルを削除すると、アプリがクラッシュするのはなぜですか?

ありがとう!

マーティンR

sectionNameKeyPath:フェッチされた結果コントローラーの引数に渡されるキーパスは、Objective-Cランタイムから見える必要があります。明示的なアノテーションを必要とするSwift4では(Swift 4の#selector()で@objc推論の非推奨に対処@objcするにはどうすればよいですか?):

extension completedNotes {
    @objc var sectionIdentifier : String? { 
        // ...
    }
}

それがないと、セクション名のキーパスは黙って無視されます。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

swift4でUIImagePickerControllerを使用する方法

分類Dev

swift4を使用してJSONを解析する方法

分類Dev

Codableを使用してSwift4で複雑なJSONを解析する方法

分類Dev

Alamofireとデコードを使用してJSONを取得する-Swift4

分類Dev

すべてのデバイスでswift4を使用してCollectionViewに2つの列を表示する方法

分類Dev

すべてのデバイスでswift4を使用してCollectionViewに3つの列を表示する方法

分類Dev

iOS Swift4 DateFormatter()のみを使用して短い平日を印刷する方法は?

分類Dev

Swift4 / 5を使用して複数のクラスを拡張する方法

分類Dev

Alamofire Swift4を使用してUICollectionViewに画像を入力する方法

分類Dev

swift4を使用してgooglemap apiを呼び出す方法は?

分類Dev

Alamofireを使用してSwift4でYoutubeAPIを解析します

分類Dev

動的キーを使用してSwift4でネストされたJSONからデータを抽出する方法

分類Dev

Swift4のアンカーを使用してプログラムでUIScrolllViewにビューを追加する方法

分類Dev

swift4でUItextfieldを使用するUISearchbar

分類Dev

swift4でNSSetUncaughtExceptionHandlerを使用する

分類Dev

swift3でfetchedResultsControllerを使用する

分類Dev

Swift4:UITableViewControllerでreloadDataとdeselectRowを使用する方法は?

分類Dev

Couchbaseを使用してSwift4のデータベースオブザーバーを介してデータを取得する方法は?

分類Dev

ChildAddedを使用して、Swift4でFirebaseデータベースから最初のキーを取得します

分類Dev

Swift4を使用してプログラムでNSLayoutConstraintsを使用してUIViewをUITableViewControllerに追加する

分類Dev

swift4の少し複雑なjsonからデータを解析して取得する方法は?

分類Dev

Swift4のwhereクエリを使用してFirebaseからデータを取得する

分類Dev

Swift4で画像またはボタンから文字列を選択してJSONURLを取得する

分類Dev

Swift4を使用してUICollectionビューで複数の選択を取得するにはどうすればよいですか

分類Dev

配列にswift4を使用してリモートURLからjsonデータを取得する正しい方法

分類Dev

Swift4でSwift3の廃止された構文を使用する方法

分類Dev

Swift4を使用してARKitで仮想オブジェクトを回転させる方法

分類Dev

NSDictionary swift4から重要なデータを取得する方法

分類Dev

fontAwesomeを使用してカスタムアイコンをSwift4のUIbuttonに追加する方法

Related 関連記事

  1. 1

    swift4でUIImagePickerControllerを使用する方法

  2. 2

    swift4を使用してJSONを解析する方法

  3. 3

    Codableを使用してSwift4で複雑なJSONを解析する方法

  4. 4

    Alamofireとデコードを使用してJSONを取得する-Swift4

  5. 5

    すべてのデバイスでswift4を使用してCollectionViewに2つの列を表示する方法

  6. 6

    すべてのデバイスでswift4を使用してCollectionViewに3つの列を表示する方法

  7. 7

    iOS Swift4 DateFormatter()のみを使用して短い平日を印刷する方法は?

  8. 8

    Swift4 / 5を使用して複数のクラスを拡張する方法

  9. 9

    Alamofire Swift4を使用してUICollectionViewに画像を入力する方法

  10. 10

    swift4を使用してgooglemap apiを呼び出す方法は?

  11. 11

    Alamofireを使用してSwift4でYoutubeAPIを解析します

  12. 12

    動的キーを使用してSwift4でネストされたJSONからデータを抽出する方法

  13. 13

    Swift4のアンカーを使用してプログラムでUIScrolllViewにビューを追加する方法

  14. 14

    swift4でUItextfieldを使用するUISearchbar

  15. 15

    swift4でNSSetUncaughtExceptionHandlerを使用する

  16. 16

    swift3でfetchedResultsControllerを使用する

  17. 17

    Swift4:UITableViewControllerでreloadDataとdeselectRowを使用する方法は?

  18. 18

    Couchbaseを使用してSwift4のデータベースオブザーバーを介してデータを取得する方法は?

  19. 19

    ChildAddedを使用して、Swift4でFirebaseデータベースから最初のキーを取得します

  20. 20

    Swift4を使用してプログラムでNSLayoutConstraintsを使用してUIViewをUITableViewControllerに追加する

  21. 21

    swift4の少し複雑なjsonからデータを解析して取得する方法は?

  22. 22

    Swift4のwhereクエリを使用してFirebaseからデータを取得する

  23. 23

    Swift4で画像またはボタンから文字列を選択してJSONURLを取得する

  24. 24

    Swift4を使用してUICollectionビューで複数の選択を取得するにはどうすればよいですか

  25. 25

    配列にswift4を使用してリモートURLからjsonデータを取得する正しい方法

  26. 26

    Swift4でSwift3の廃止された構文を使用する方法

  27. 27

    Swift4を使用してARKitで仮想オブジェクトを回転させる方法

  28. 28

    NSDictionary swift4から重要なデータを取得する方法

  29. 29

    fontAwesomeを使用してカスタムアイコンをSwift4のUIbuttonに追加する方法

ホットタグ

アーカイブ