肇鑫的技术博客

业精于勤,荒于嬉

SwiftUI Preview Crashed Issue With Exception `RLMException`. Reason: This method may only be called on RLMArray instances retrieved from an RLMRealm.

After investigation, I found that this issue was caused by sorted method with keyPath.

List { // this list crashes
    ForEach(dayList.items.sorted(by: \.startDate, ascending: true)) { currentItem in
        ItemRowSwiftUIView(currentItem: currentItem)
    }.onDelete(perform: { indexSet in
        removeItems(atOffsets: indexSet)
    })
}
    
List { // this list doesn't crash
    ForEach(dayList.items.sorted(by: {
        $0.startDate < $1.startDate
    })) { currentItem in
        ItemRowSwiftUIView(currentItem: currentItem)
    }.onDelete(perform: { indexSet in
        removeItems(atOffsets: indexSet)
    })
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(dayList: DayList())
    }
}

When using the keyPath to sort, the preview crashed. That because sorted by keyPath used realm and for a unmanaged object dayList, there is no realm.

So we need to create a realm first.

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(dayList: createRealmAndGetDayList())
    }

    static func createRealmAndGetDayList() -> DayList {
        let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "for debug"))
        let dayList = DayList()
        
        try! realm.write({
            realm.add(dayList, update: .all)
        })

        return dayList
    }
}

Then everything will work.