![](/img/trans.png)
[英]CoreData can't save Object when non-Optional value is set in willSave()
[英]How to save a optional value in a variable to another non optional object
var ret: ServiceQuestion?
ret = currentQuestion
return ret ?? ServiceQuestion()
当我像上面一样使用它时它工作正常但是当我将代码更改为
var ret = ServiceQuestion()
ret = currentQuestion
return ret
然后它开始在当前问题变量Value of optional type 'ServiceQuestion?'上给出错误未解开;
我需要实现第二种方式我怎样才能摆脱这个问题
控制台上的错误 Cityworks [8230:187999] [错误] 错误:CoreData:错误:无法在 NSManagedObject 类“ServiceRequestQuestion”上调用指定的初始值设定项
您不能在非可选变量中保存可选值。
你必须打开它。
有很多方法可以做到这一点。
最简单(也是最危险)的是... ret = currentQuestion!
.
但是如果currentQuestion
为零,这将崩溃。 您必须决定如何打开它。
由于ret
不再是可选的,您可以在??
操作员:
var ret = ServiceQuestion()
ret = currentQuestion ?? ret
然而,这将分配ServiceQuestion
将保持不使用时currentQuestion
具有价值,那么你的第一个代码片段更有效。 也更容易理解。
您可以为此使用强制展开:
return currentQuestion!
...但是你不应该使用强制解包,只有在你绝对确定值永远不会nil
非常狭窄和专用的情况下。
为什么? 因为如果该值为nil
,您的应用程序将崩溃。 考虑将返回值更改为 optional 。
你可以这样使用它:-
var serviceQuestion = ServiceQuestion()
if let currentQuestion:ServiceQuestion = currentQuestion {
serviceQuestion = currentQuestion
}
return serviceQuestion
var ret = ServiceQuestion()
ret = currentQuestion
return ret
您收到此错误是因为 ret 是非可选变量,但 currentQuestion 是可选的,并且您将可选变量分配给非可选变量。
你需要做
var serviceQuestion = ServiceQuestion()
if let currentQuestion = currentQuestion {
serviceQuestion = currentQuestion
}
return serviceQuestion
或者
var serviceQuestion = ServiceQuestion()
if currentQuestion != nil {
serviceQuestion = currentQuestion!
}
return serviceQuestion
如果你这样做
var serviceQuestion = ServiceQuestion()
serviceQuestion = currentQuestion!
return serviceQuestion
当 currentQuestion 为零时它可能会崩溃
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.