Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/103.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在CoreData应用程序中设置值_Ios_Swift_Core Data_Nsunknownkeyexception - Fatal编程技术网

Ios 在CoreData应用程序中设置值

Ios 在CoreData应用程序中设置值,ios,swift,core-data,nsunknownkeyexception,Ios,Swift,Core Data,Nsunknownkeyexception,好的,我已经做了大量的搜索,我发现的一切似乎都与视图控制器和它们上的链接不工作或没有连接有关。那不是我的问题。我有一个应用程序,它使用CoreData来记录表格列表、表格编号、是否干净以及是否正在使用。但是,当我尝试使用setValue()函数更改属性的键值时,它会使我的应用程序崩溃,并显示以下崩溃报告 2018-04-02 21:45:15.840265-0500 Trakr[26636:1455153] *** Terminating app due to uncaught exceptio

好的,我已经做了大量的搜索,我发现的一切似乎都与视图控制器和它们上的链接不工作或没有连接有关。那不是我的问题。我有一个应用程序,它使用CoreData来记录表格列表、表格编号、是否干净以及是否正在使用。但是,当我尝试使用setValue()函数更改属性的键值时,它会使我的应用程序崩溃,并显示以下崩溃报告

2018-04-02 21:45:15.840265-0500 Trakr[26636:1455153] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSManagedObjectContext 0x6040001c4fb0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key inUse.'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010d1af1e6 __exceptionPreprocess + 294
1   libobjc.A.dylib                     0x0000000108f3d031 objc_exception_throw + 48
2   CoreFoundation                      0x000000010d1af0b9 -[NSException raise] + 9
3   Foundation                          0x000000010895eb47 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 292
4   Trakr                               0x0000000108615bee _T05Trakr24CheckTableViewControllerC18inUseSwitchChangedyypF + 846
5   Trakr                               0x0000000108615e41 _T05Trakr24CheckTableViewControllerC18inUseSwitchChangedyypFTo + 81
6   UIKit                               0x000000010ac1a448 -[UIApplication sendAction:to:from:forEvent:] + 83
7   UIKit                               0x000000010ad95804 -[UIControl sendAction:to:forEvent:] + 67
8   UIKit                               0x000000010ad95b21 -[UIControl _sendActionsForEvents:withEvent:] + 450
9   UIKit                               0x000000010b8d6d60 -[UISwitchModernVisualElement sendStateChangeActions] + 73
10  UIKit                               0x000000010b29889f -[UISwitchMVEGestureTrackingSession _sendStateChangeActionsIfNecessary] + 63
11  UIKit                               0x000000010b8d74ec -[UISwitchModernVisualElement _handleLongPressWithGestureLocationInBounds:gestureState:] + 760
12  UIKit                               0x000000010b21141b -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + 57
13  UIKit                               0x000000010b21a1f0 _UIGestureRecognizerSendTargetActions + 109
14  UIKit                               0x000000010b217a38 _UIGestureRecognizerSendActions + 307
15  UIKit                               0x000000010b216c8c -[UIGestureRecognizer _updateGestureWithEvent:buttonEvent:] + 859
16  UIKit                               0x000000010b1fbcf0 _UIGestureEnvironmentUpdate + 1329
17  UIKit                               0x000000010b1fb773 -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] + 484
18  UIKit                               0x000000010b1fa875 -[UIGestureEnvironment _updateGesturesForEvent:window:] + 281
19  UIKit                               0x000000010ac9080b -[UIWindow sendEvent:] + 4064
20  UIKit                               0x000000010ac34370 -[UIApplication sendEvent:] + 352
21  UIKit                               0x000000010b57557f __dispatchPreprocessedEventFromEventQueue + 2796
22  UIKit                               0x000000010b578194 __handleEventQueueInternal + 5949
23  CoreFoundation                      0x000000010d151bb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
24  CoreFoundation                      0x000000010d1364af __CFRunLoopDoSources0 + 271
25  CoreFoundation                      0x000000010d135a6f __CFRunLoopRun + 1263
26  CoreFoundation                      0x000000010d13530b CFRunLoopRunSpecific + 635
27  GraphicsServices                    0x000000010fa46a73 GSEventRunModal + 62
28  UIKit                               0x000000010ac190b7 UIApplicationMain + 159
29  Trakr                               0x000000010861e697 main + 55
30  libdyld.dylib                       0x000000010e318955 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
最后


有人能告诉我为什么这不起作用吗?我一辈子都无法理解它….

您应该创建NSManagedObject的
子类,而不是使用KVC。然后可以直接在“表”实例中设置该值

另外,您正在将值设置为
context.setValue(:)
,您应该创建
表的entityDescription,如下所示

var newTable = NSEntityDescription.insertNewObject(forEntityName: "Table", into: PersistenceService.context)
newTable.setValue(fale, forKey: "isClean")

非常感谢。然而,我还发现调用PersistenceService.saveContext()实际上是在保存数据,尽管据我所知,我还没有修改上下文。这是如何发生的?这应该是
实体实例
,而不是设置值的
NSManagedObjectContext实例
import Foundation
import CoreData

class PersistenceService {
// MARK: - Core Data stack

private init() {}

static var context: NSManagedObjectContext {
    return persistentContainer.viewContext
}

static var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "tableModel")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

static func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
            print("Saved to CoreData")
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}
}
var newTable = NSEntityDescription.insertNewObject(forEntityName: "Table", into: PersistenceService.context)
newTable.setValue(fale, forKey: "isClean")