English 中文(简体)
以其他方式创建具有Xcode preview(iOS 17+)衍生特性的流层持久性储存
原标题:Alternative way to create a in-memory persistent store with derived attribute for Xcode preview(iOS 17+)

我正在实施一项项目,开发一个SOS仪器和植被延伸(iOS 17+和Xcode 15),并利用核心Data来管理用户数据,我最后做了修改:对我的用户实体的从属性日期,然而,由于未有例外的NSInvalidArgumentExcept,在我试图为审查提供商制作一个模拟数据时,该固定储存不会造成故障。 理由: 所提供的核心数据并不支持衍生的。

And my code:

import WidgetKit
import SwiftUI
import Intents
import AppIntents
import CoreData

struct WidgetDetailsProvider: AppIntentTimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        return SimpleEntry(date: .now)
    }
    
    func snapshot(for configuration: UserInfoWidgetIntent, in context: Context) async -> SimpleEntry {
        return SimpleEntry(date: .now)
    }
    
    func timeline(for configuration: UserInfoWidgetIntent, in context: Context) async -> Timeline<SimpleEntry> {
        let entry = SimpleEntry(date: Date())
        let timeline = Timeline(entries: [entry], policy: .never)
        return timeline
    }
}

struct UserInfoWidgetIntent: WidgetConfigurationIntent {
    static var title: LocalizedStringResource = "Test"
    static var description: IntentDescription = IntentDescription("Test description")
    
    @Parameter(title: "Display in full name")
    var isDisplayFullname: Bool
    
    init(isDisplayFullname: Bool) {
        self.isDisplayFullname = isDisplayFullname
    }
    
    init() {}
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let isDisplayFullname: Bool
}

struct UserInfoWidgetEntryView : View {
    var entry: WidgetDetailsProvider.Entry
    @FetchRequest(sortDescriptors: [SortDescriptor(.lastModify, order: .reverse)]) var userInfo: FetchedResults<UserInfo>

    var body: some View {
        VStack {
            Text(entry.date, style: .time)
                .frame(alignment: .leading)
            HStack {
                if userInfo.isEmpty {
                    Text("The list is Empty")
                }
                ForEach(userInfo) {user in
                    if entry.isDisplayFullname {
                        Text(user.fullname)
                    } else {
                        Text(user.name)
                    }
                }
            }
            
            
        }.containerBackground(for: .widget) {
            Color.white
        }
    }
}

struct UserInfoWidget: Widget {
    let kind: String = "UserInfoWidgetIntent"

    var body: some WidgetConfiguration {
        AppIntentConfiguration(
            kind: kind,
            intent: UserInfoWidgetIntent.self,
            provider: WidgetDetailsProvider()) { entry in
            UserInfoWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
        .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
    }
}

struct UserInfoWidget_Previews: PreviewProvider {
    static var previews: some View {
        let dummyContainer: NSPersistentContainer = {
            let container = NSPersistentContainer(name: "UserModel")
            let description = NSPersistentStoreDescription()
            description.type = NSInMemoryStoreType
            container.persistentStoreDescriptions = [description]
            container.loadPersistentStores {description, error in
                if let error = error {
                    print("Failed to load: (error)")
                }
            }
            let dummy = Barcode(context: container.viewContext)
            dummy.username = "foo"
            do {
                try container.viewContext.save()
            } catch {
                fatalError("Failed to save entity.")
            }
            return container
        }()
        
        UserInfoWidgetEntryView(entry: SimpleEntry(date: Date()))
            .previewContext(WidgetPreviewContext(family: .systemMedium))
            .environment(.managedObjectContext, dummyContainer.viewContext)
    }
}

Eventually I remove the derived attribute and it work just fine, but I am wondering it is have other way to avoid this problem? Is there any way to preview coreData entity with derived attribute? Thank you.

Update 12/1: The error message of crash is: UserInfoWidgetExtension crashed due to an uncaught exception NSInvalidArgumentException . Reason: Core Data provided atomic stores do not support derived. And update the code of UserInfoWidget.swift.

Update 15/1: Thanks to @loremipsum suggestion and it work well with following code:

let dummyContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "UserInfoModel")
    let description = NSPersistentStoreDescription()
    //description.type = NSInMemoryStoreType
    description.url = URL(fileURLWithPath: "/dev/null")
    container.persistentStoreDescriptions = [description]
    container.loadPersistentStores {description, error in
        if let error = error {
            print("Failed to load: (error)")
        }
    }
    let dummy = UserInfo(context: container.viewContext)
    dummy.name = "foo"
    dummy.fullname = "dummy foo"
    do {
        try container.viewContext.save()
    } catch {
        fatalError("Failed to save entity.")
    }
    return container
}()

USerInfoWidgetEntryView(entry: SimpleEntry(date: Date()))
                .previewContext(WidgetPreviewContext(family: .systemSmall))
                .environment(.managedObjectContext, dummyContainer.viewContext)
问题回答

有两种办法可使用中间集装箱。

一种是使用NSInMemoryStoreType/code>。

description.type = NSInMemoryStoreType

而另一则通过制定<代码>null

description.url = URL(fileURLWithPath: "/dev/null")

已知第一种方式有多种限制,如碎块删除,其次,是 Apple果在标准<代码>上制造一个审查集装箱的用意,即X编码创建的“PersistentController





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

Iphone NSTimer Issue

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the ...

Include a .txt file in a .h in C++?

I have a number of places where I need to re-use some template code. Many classes need these items In a .h could I do something like: #include <xxx.txt> and place all of this code in the ....

Iterating over string/strlen with umlauted characters

This is a follow-up to my previous question . I succeeded in implementing the algorithm for checking umlauted characters. The next problem comes from iterating over all characters in a string. I do ...

Xcode open two editor windows with same file

Is it possible to open the same file in two separate windows in Xcode. I can open a file in one window and the same file in the main Xcode editor window, but I wanted two separate fulltime editor ...

Forcing code signing refresh in Xcode

In our environment, we share resources across multiple projects and platforms. When building for iPhone, only a subset of those resources are needed. Since that subset is still considerable, we have ...

热门标签