【发布时间】:2019-03-09 16:44:52
【问题描述】:
我正在使用一个 NSTextField,我通过情节提要中的绑定将其绑定到一个整数。 Swift 代码如下所示:
@objc dynamic var quantity: Int = 0
这非常适合验证数字,如果尝试输入无效的内容(例如字母),我会收到一条有用的消息。
我遇到的问题是,当您在未填写任何内容的情况下退出该字段时,应用程序崩溃了。在错误消息之后,最相关的似乎是:
2019-03-09 16:29:46.813928+0000 ViewWebSocketLearning[34535:1969855] [General] [<ViewWebSocketLearning.OrderFormViewController 0x103131820> setNilValueForKey]: could not set nil as the value for the key show.
2019-03-09 16:29:46.825146+0000 ViewWebSocketLearning[34535:1969855] [General] (
0 CoreFoundation 0x00007fff3d7b6ded __exceptionPreprocess + 256
1 libobjc.A.dylib 0x00007fff69882720 objc_exception_throw + 48
2 CoreFoundation 0x00007fff3d7b6c1f +[NSException raise:format:] + 201
3 Foundation 0x00007fff3fbe8dbb -[NSObject(NSKeyValueCoding) setNilValueForKey:] + 81
4 Foundation 0x00007fff3fac1450 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 331
5 Foundation 0x00007fff3faec38a -[NSObject(NSKeyValueCoding) setValue:forKeyPath:] + 271
6 AppKit 0x00007fff3af0bf03 -[NSBinder _setValue:forKeyPath:ofObject:mode:validateImmediately:raisesForNotApplicableKeys:error:] + 473
7 AppKit 0x00007fff3af0bccf -[NSBinder setValue:forBinding:error:] + 236
8 AppKit 0x00007fff3b54c376 -[NSValueBinder _applyObjectValue:forBinding:canRecoverFromErrors:handleErrors:typeOfAlert:discardEditingCallback:otherCallback:callbackContextInfo:didRunAlert:] + 225
9 AppKit 0x00007fff3b54c698 -[NSValueBinder applyDisplayedValueHandleErrors:typeOfAlert:canRecoverFromErrors:discardEditingCallback:otherCallback:callbackContextInfo:didRunAlert:error:] + 544
10 AppKit 0x00007fff3b54c81a -[NSValueBinder _applyDisplayedValueIfHasUncommittedChangesWithHandleErrors:typeOfAlert:discardEditingCallback:otherCallback:callbackContextInfo:didRunAlert:error:] + 105
11 AppKit 0x00007fff3b053e4e -[NSValueBinder validateAndCommitValueInEditor:editingIsEnding:errorUserInterfaceHandled:] + 460
12 AppKit 0x00007fff3b053c5a -[_NSBindingAdaptor _validateAndCommitValueInEditor:editingIsEnding:errorUserInterfaceHandled:bindingAdaptor:] + 175
13 AppKit 0x00007fff3b053b8d -[_NSBindingAdaptor validateAndCommitValueInEditor:editingIsEnding:errorUserInterfaceHandled:] + 240
14 AppKit 0x00007fff3af83e2b -[NSTextField textShouldEndEditing:] + 368
15 AppKit 0x00007fff3af44cc9 -[NSTextView(NSSharing) resignFirstResponder] + 499
16 AppKit 0x00007fff3ada2522 -[NSWindow _realMakeFirstResponder:] + 258
17 AppKit 0x00007fff3b058001 -[NSTextView(NSPrivate) _giveUpFirstResponder:] + 263
我将此解释为 NSTextField 绑定不接受 nil 条目,这显然是由于将字段留空所致。
如何防止此异常发生?对于我的应用程序,在处理其他内容时将该字段留空是完全可以的。
【问题讨论】:
-
在文本字段中添加数字格式化程序。
-
错误说崩溃与密钥
show有关,而不是与quantity有关。quantity是非可选的,不能是nil。 -
非可选整数绑定(直接)到文本字段不会崩溃,
0显示为"0" -
@MarekH 原因一定在其他地方。您不能将
nil分配给非可选类型,正如我所说,SwiftInt值0不被视为nil -
@MarekH,如果您想回答这个问题,我会将您的回答标记为解决方案。
标签: macos cocoa swift4 nstextfield kvc