从目标C到SWIFT-以前的核心数据内容未加载

发布于 2025-02-03 03:57:19 字数 3230 浏览 0 评论 0原文

我正在尝试迁移我的应用程序,该应用程序使用目标C现在使用Swift。我没有错误,但没有在应用程序中加载信息。我已经将旧模型导入了新应用程序中的新项目

核心数据存储

init(inMemory: Bool = false) {
    container = NSPersistentCloudKitContainer(name: "Medicine_Tracker")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    container.viewContext.automaticallyMergesChangesFromParent = true
}

中,并使用以下内容在视图中加载了 。 NSLOG结果计数:0,而应该为项目计数:2

struct MedicineView: View {

@Environment(\.managedObjectContext) private var viewContext

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Medicine.name, ascending: true)],
    animation: .default)
private var items: FetchedResults<Medicine>

var body: some View {
    NavigationView {
        List {
            ForEach(items) { item in
                NavigationLink(destination: MedicineDetailView(medicine: item)) {
                    Text("\(item.name ?? "Error")")
                }
            }
        }
        .navigationBarTitle("Medicines", displayMode: .inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                NavigationLink(destination: MedicineAddView()) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
        .onAppear() {
            NSLog("Item Count: \(items.count)")
        }
    }
}

}

,旧应用程序使用

- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Medicine_Tracker" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return __managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Medicine_Tracker.sqlite"];
    
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
    
    return __persistentStoreCoordinator;
}

I'm trying to migrate an app of mine that was using objective c to now use swift. I'm getting no errors but its not loading the information previously in the app. I've imported the old model into the new project

In the new app its loading the core data store using

init(inMemory: Bool = false) {
    container = NSPersistentCloudKitContainer(name: "Medicine_Tracker")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    container.viewContext.automaticallyMergesChangesFromParent = true
}

and loaded in the view using the below. The NSLog results in Item Count: 0 whereas it should be Item Count: 2

struct MedicineView: View {

@Environment(\.managedObjectContext) private var viewContext

@FetchRequest(
    sortDescriptors: [NSSortDescriptor(keyPath: \Medicine.name, ascending: true)],
    animation: .default)
private var items: FetchedResults<Medicine>

var body: some View {
    NavigationView {
        List {
            ForEach(items) { item in
                NavigationLink(destination: MedicineDetailView(medicine: item)) {
                    Text("\(item.name ?? "Error")")
                }
            }
        }
        .navigationBarTitle("Medicines", displayMode: .inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                NavigationLink(destination: MedicineAddView()) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
        .onAppear() {
            NSLog("Item Count: \(items.count)")
        }
    }
}

}

and the old app uses

- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Medicine_Tracker" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return __managedObjectModel;
}

// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil) {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Medicine_Tracker.sqlite"];
    
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
    
    return __persistentStoreCoordinator;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文