SwiftUI TabView 在添加/删除 CoreData 元素期间给出错误消息

人气:1,022 发布:2022-10-16 标签: swiftui swift uitableview core-data swiftui-tabview

问题描述

我目前正在尝试将 TabView 用于带有 CoreData 的轮播视图(PageTabViewStyle).

I am currently trying to use TabView for carousel view(PageTabViewStyle) with CoreData.

错误不会发生,当我添加一个新页面时,像这样 age.name: 3, page.name: 4, page.name: 5

The error doesn't occur, when I add a new page in order like this age.name: 3, page.name: 4, page.name: 5

但是发生错误,如果我在第一个/中间顺序放一个数字,比如 page.name: 2

But the error occurs, if I put a number in the first/middle order like page.name: 2

如果我输入 page.name: 6,则没有错误,Alphabet 也是如此.b c d e ->输入f",没问题,但输入a"错误.

If I put page.name: 6, then no error and it's also same with Alphabet. b c d e -> put "f", no problem, but put "a" error.

关闭应用程序并打开应用程序后,我仍然看到更新的(页面添加/页面删除)ContentView.

After turn off the app and open the app, then I see the updated(Page added/Page deleted) ContentView anyway.

我猜,TabView有排序问题,所以我尝试对CoreData的列表进行排序,将LifeCycle改为SwiftUI,但错误一再出现.我也试过 Firebase,但同样的问题.

I guess, TabView has a sorting problem, so I tried to sort the list of CoreData, change LifeCycle to SwiftUI, but the error occurs again and again. I've also tried with Firebase, but the same problem.

错误信息:

"libc++abi: terminating with uncaught exception of type NSException
    *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'attempt to delete item 1 from section 0 which only contains 1 items before the update'
    terminating with uncaught exception of type NSException"  

内容视图

TabView() {
    ForEach(pages, id: \.self) { page in
        SubPage(whichPage: page)
    }
}
.tabViewStyle(PageTabViewStyle())
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))

添加页面

let page = Page(context: self.moc)
        page.name = pageName

        do {
            print("page.name: \(page.name ?? "Unknown")")
            try self.moc.save()
            
        } catch {
            print(error)
        }

子页面

@FetchRequest(entity: Page.entity(),
              sortDescriptors: [NSSortDescriptor(keyPath: \Page.name, ascending: true)]
) var pages: FetchedResults<Page>

var whichPage: FetchedResults<Page>.Element

使用 VStack 或 HStack 或 List 代替 TabView 工作正常,没有任何问题.

Using VStack or HStack or List instead of TabView works fine without any problem.

推荐答案

这个问题终于在 Xcode 13 & 中解决了基于 iOS 15!

Finally, this problem is solved in Xcode 13 & iOS 15 based!

完整代码

TabView {
    ForEach(pages) { page in
        SubPage(whichPage: page)
    }
}
.tabViewStyle(PageTabViewStyle())

TabView {
    ForEach(pages) { page in
        SubPage(whichPage: page)
    }
}
.tabViewStyle(.page)

325