如何限制coredata中空值的输入?
我正在研究基于XMLparsing的项目,我使用coredata来存储url。
但是有些时候coredata输入的空值我不知道为什么会出现这种类型的问题。
这是我尝试过的代码。
- (void)feedParserDidFinish:(MWFeedParser *)parser { NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"demo"]; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"urloffeed = %@", self.Feedlink]; NSManagedObjectContext *context = [self managedObjectContext]; if ([[context executeFetchRequest:fetchRequest error:NULL] count] == 0) { // Create a new managed object NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"demo" inManagedObjectContext:context]; [newDevice setValue:self.Name forKey:@"nameofentry"]; [newDevice setValue:self.WebsiteName forKey:@"sitename"]; [newDevice setValue:self.Feedlink forKey:@"urloffeed"]; NSError *error = nil; // Save the object to persistent store if (![context save:&error]) { NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]); } }
有人请帮我解决这个问题吗?
将宏定义为。
#define IS_NOT_NIL_OR_NULL(value) (value != nil && value != Nil && value != NULL && value != (id)[NSNull null])
在将核心数据中的值保存之前,请检查null的值。
if ([[context executeFetchRequest:fetchRequest error:NULL] count] == 0) { // Create a new managed object NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"demo" inManagedObjectContext:context]; if (IS_NOT_NIL_OR_NULL(self.Name)) { [newDevice setValue:self.Name forKey:@"nameofentry"]; } else { // Handle else case . get self.name value is null here . } if (IS_NOT_NIL_OR_NULL(self.WebsiteName)) { [newDevice setValue:self.WebsiteName forKey:@"sitename"]; } else { // Handle else case . get self.WebsiteName value is null here . } if (IS_NOT_NIL_OR_NULL(self.Feedlink)) { [newDevice setValue:self.Feedlink forKey:@"urloffeed"]; } else { // Handle else case . get self.Feedlink value is null here . } NSError *error = nil; // Save the object to persistent store if (![context save:&error]) { NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]); } }
希望它对你有所帮助。
您可以使用此表达式检查“null”值,如果值为“null”,则只需插入空值,否则传递您获得的值。 非常简单的代替“strname”只是传递你的键值。
if (strname == nil || strname == (id)[NSNull null]) { cell.lbltitle.text=@""; }
那么从CoreData属性编辑器中取消选中Optional
呢?