问题
I want to test if an NSNumber attribute of a NSManageObject Subclass has been set or not. Note, that the attribute is of NSNumber / Integer16 I have tried several approaches but none worked (these below always evaluate to false):
// 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];
}
Can anyone enlighten me and explain me why these are not working?
回答1:
The solution is to set the attribute in core data as required with a default value and to test with this code:
if (!patient.zyklus_laenge) {
self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%d", 28];
} else {
self.zyklusLaengeTextField.text = [NSString stringWithFormat:@"%@", patient.zyklus_laenge];
}
回答2:
If you have a default value set for the attribute, it will be that default value, which is normally 0, not null.
If so, you can check the following:
if (patient.zyklus_laenge.intValue == 0)
Otherwise, this null check can be used:
if (patient.zyklus_laenge != nil)
回答3:
id value = patient.zyklus_laenge;
if (value == [NSNull class])
to
id value = patient.zyklus_laenge;
if ([value isKindOfClass:[NSNull class]])
来源:https://stackoverflow.com/questions/26611823/how-can-i-test-if-an-attribute-of-a-coredata-object-is-null