如何测试Core Data对象的属性是否为null?

时间:2014-10-28 15:12:10

标签: ios objective-c core-data nsmanagedobject

我想测试是否已设置NSManageObject子类的NSNumber属性。注意,该属性是NSNumber / Integer16 我尝试了几种方法,但没有一种方法(以下总是评估为假):

// Note: patient.zyklus_laenge is of NSNumber (Integer16)
// does not work
id value = patient.zyklus_laenge;
if (value == [NSNull null]) {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}
// does not work
if (!patient.zyklus_laenge) {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}
// does not work
if ([patient.zyklus_laenge isEqual:nil]) {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}
// does not work
if (patient.zyklus_laenge == nil) {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}

任何人都可以启发我并解释为什么这些不起作用?

3 个答案:

答案 0 :(得分:0)

id value = patient.zyklus_laenge;
if (value == [NSNull class]) 

id value = patient.zyklus_laenge;
if ([value isKindOfClass:[NSNull class]])

答案 1 :(得分:0)

解决方案是根据需要使用默认值设置核心数据中的属性,并使用以下代码进行测试:

if (!patient.zyklus_laenge) {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
    self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}

答案 2 :(得分:0)

如果您为该属性设置了默认值,那么它将是该默认值,通常为0,而不是null。

如果是,您可以查看以下内容:

if (patient.zyklus_laenge.intValue == 0)

否则,可以使用此空检查:

if (patient.zyklus_laenge != nil)