如何在swift中检查@NSManaged属性是否为nil?

时间:2015-08-07 00:01:39

标签: ios swift parse-platform

我正在向现有数据集添加新属性。如果我从Parse.com后端获得的该属性的值不存在,我需要采取纠正措施(例如将其设置为默认值)。我已经通过这里发布的各种解决方案并且它们不起作用,我在下面的代码中将Xcode错误消息作为注释。我已经在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


}
}

}

1 个答案:

答案 0 :(得分:2)

由于这必须是与Objective-C兼容的属性,如果您在Objective-C中编写此代码,请执行您的操作!在Objective-C中,Bool不能是nil - 它不是一个对象。相反,您使用NSNumber,它具有保存布尔值(init(bool:))和提取布尔值(boolValue)的方法。因此,请将其设为NSNumber?并相应地调整其余代码。