简体   繁体   English

如何快速检查@NSManaged属性是否为nil?

[英]How to check if an @NSManaged property is nil in swift?

I am adding a new property to an existing data set. 我正在向现有数据集添加新属性。 I need to take corrective action (such as setting it to a default value) if the value for that property that I get from my Parse.com backend does not exist. 如果我从Parse.com后端获取的该属性的值不存在,则需要采取纠正措施(例如将其设置为默认值)。 I have gone through various solutions posted here and they do not work, I have put the Xcode error message as comments in the code below. 我已经经历了这里发布的各种解决方案,但是它们不起作用,我将Xcode错误消息作为注释放在下面的代码中。 I have tried it both in Xcode 6.4 and in Xcode 7.0 beta 5 as another post had suggested that optional NSManaged is properly handled in Xcode 7.0 Beta 2. 我在Xcode 6.4和Xcode 7.0 beta 5中都尝试过,因为另一篇文章建议在Xcode 7.0 Beta 2中正确处理可选的NSManaged。

class MyObject: PFObject, PFSubclassing {
@NSManaged private(set) var newPoperty: Bool // No probs here but cannot check nil, see later on..
// @NSManaged private(set) var newProperty: Bool? // ! Property cannot be marked NSManaged as its type cannot be represented in Objective-C

private func initLaterProperties(object: MyObject) {

if (object.newProperty == nil ) {//Does not work with following messages
// Xcode 7.0 Beta 5: ! Binary operator '==' cannot be applied to operands of type Bool and nil
// Xcode 6.4: No operator found matching the operands



// Do something
}

if let test = object.newProperty { // Does not work with following message
//! Initializer for conditional binding must have Optional type, not 'Bool'
}
else {
//Do something


}
}

}

Since this has to be an Objective-C-compatible property, do what you would have done if you had been writing this code in Objective-C! 由于这必须是与Objective-C兼容的属性,因此,如果您在Objective-C中编写此代码,则应执行本操作! In Objective-C, a Bool cannot be nil - it is not an object. 在Objective-C中,布尔不能为nil它不是对象。 Instead, you'd use NSNumber, which has methods to hold a boolean ( init(bool:) ) and to extract a boolean ( boolValue ). 相反,您将使用NSNumber,该方法具有保存布尔值( init(bool:) )和提取布尔值( boolValue )的方法。 So make this an NSNumber? 因此,使它成为NSNumber? and adjust the rest of your code accordingly. 并相应地调整其余代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM