检查Core Data managedObject中的多个nil值? [英] Check for multiple nil values in Core Data managedObject?

查看:166
本文介绍了检查Core Data managedObject中的多个nil值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在保存之前检查我的 managedObjectContext 中是否有 nil 值。在那一刻,我正在使用 if 语句对每个密钥进行测试。我的 NGLS 实体中有很多属性,因此您可以看到测试每个键 nil 值似乎不大非常实用。

  if([_managedObjectNGLS valueForKey:@q1] == nil){
[_managedObjectNGLS setValue:@ forKey:@q1];
}
if([_managedObjectNGLS valueForKey:@q1More] == nil){
[_managedObjectNGLS setValue:@forKey:@q1More];
}
....

//保存managedObject
NSError *错误;
[[self.managedObjectNGLS managedObjectContext] save:& error];
NSLog(@%@,self.managedObjectNGLS);
NSLog(@数据保存);

通常有很多 nil 值,我需要手动更改许多 if语句。有没有办法批量测试我的实体中的所有对象的nil值?如果是这样,有没有办法立即用一组字符串替换所有这些?谢谢。

解决方案

核心数据包括强大的验证功能。作为保存的一部分,Core Data验证对象属性,确保只保留有效对象。



您可以在核心数据模型编辑器,或通过实现键值验证。 / p>

例如,使用模型编辑器,您可以将属性设置为非可选属性并提供默认值:




I need to check if there any nil values in my managedObjectContext before saving them. At the minute I am doing tests on each key using if statements. I have many attributes in my NGLS entity, so as you can see testing each key for nil values doesn't seem very practical.

if ([_managedObjectNGLS valueForKey:@"q1"] == nil){
    [_managedObjectNGLS setValue:@"" forKey:@"q1"];
}
if ([_managedObjectNGLS valueForKey:@"q1More"] == nil){
    [_managedObjectNGLS setValue:@"" forKey:@"q1More"];
}
....

// Save managedObject
NSError *error;
[[self.managedObjectNGLS managedObjectContext] save:&error];
NSLog(@"%@", self.managedObjectNGLS);
NSLog(@"Data saved");

Often there are many nil values, which I need to change manually with many if statements. Is there a way to batch test all objects in my entity for nil values? And if so, is there a way to replace all of these with a set string at once? Thanks.

解决方案

Core Data includes powerful capabilities for validation. As part of a save, Core Data validates object properties, ensuring that only valid object are persisted.

You can implement validation rules in the Core Data Model Editor, or yourself in code by implementing key-value validation on your managed object subclass.

For example, using the model editor you can set a property to be non-optional and provide a default value:

这篇关于检查Core Data managedObject中的多个nil值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆