1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftData: fetchIdentifiers(_:)ではsortByは使えない

Last updated at Posted at 2025-09-13

SwiftDataでfetchIdenitfieirs(_:)によりPersistentIdentifierを取得するとき、sortByによりソート順を指定するとクエリ実行時にエラーとなります。

let identifiers = try context.fetchIdentifiers(
    FetchDescriptor<MyModel>(
        predicate: #Predicate { item in
            ...
        },
        sortBy: [SortDescriptor(\.sortColumn)]
    )
)

これは実行時に以下の例外が発生します。

SwiftDataError(_error: SwiftData.SwiftDataError._Error.sortingPendingChangesWithIdentifiers, _explanation: nil)

sortingPendingChangesWithIdentifiers

ドキュメントには説明は何もありませんが、fetchIdentifiers(_:)では対象のIDだけを読み出しているためソートはできないということでしょう。

SQL文でORDER BYをクエリに含めていればID取得でもソートできるはずだろうとは思いますが、-com.apple.CoreData.SQLDebug 1オプションを指定しても上記失敗時のクエリはログに出力されていませんでした。

対応

ソートを諦めてsortByの指定を削除するか、ソート順が必要な場合はfetch(_:)でモデルクラスを取得しましょう。

sortByを削除するとfetchIdentifiers(_:)は成功します。

let identifiers = try context.fetchIdentifiers(
    FetchDescriptor<MyModel>(
        predicate: #Predicate { item in
            ...
        },
    )
)

ソート順を指定する場合はfetch(_:)なら問題ありません。

let items = try context.fetch(
    FetchDescriptor<MyModel>(
        predicate: #Predicate { item in
            ...
        },
        sortBy: [SortDescriptor(\.sortColumn)]
    )
)
let identifiers = items.map(\.persistentModelID)

環境

確認した環境

  • iOS 18.6
  • Xcode 16.4 (16F6)
  • Swift 6.0

ドキュメント

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?