【发布时间】:2013-09-18 13:53:14
【问题描述】:
我创建了一个核心数据模型,并创建了一个类别类,其中包含用于更新和删除数据的方法。我正在尝试向该类添加验证方法并尝试使用 KVC,但有点挣扎。
我的问题是,我的验证方法仅在我实际保存上下文 [context save:&internalError] 时触发,它们工作正常,但保存过程也完成。我的问题是,什么时候触发验证可以在保存之前触发,还是我这样做完全错了?
我的代码:
+(int)doSmeThing:(InstructionMessageObject *)message inManagedObjectContext:(NSManagedObjectContext *)context error:(NSError **)error {
NSError *internalError = nil;
int timeStamp = [[NSDate date] timeIntervalSince1970];
NSManagedObject *newMessageObject = [NSEntityDescription insertNewObjectForEntityForName:@"CoreDataTable"inManagedObjectContext:context];
[newMessageObject setValue:message.productCode forKey:@"productCode"];
[newMessageObject setValue:message.quantity forKey:@"quantity"];
///////////////////////////////////////
// Need to validate HERE before save //
///////////////////////////////////////
if (![context save:&internalError]) {
*error = internalError;
return NO;
}
return YES;
}
- (BOOL)validateProductCode:(id *)ioValue error:(NSError **)outError {
*outError = nil;
if ([*ioValue integerValue] < 1 ) {
*outError = [NSError errorWithDomain:@"domain" code:101 userInfo:[NSDictionary dictionaryWithObject:@"Invalid Product Code" forKey:NSLocalizedDescriptionKey]];
return NO;
}
return YES;
}
- (BOOL)validateQuantity:(id *)ioValue error:(NSError **)outError {
*outError = nil;
if ([*ioValue integerValue] < 1 ) {
*outError = [NSError errorWithDomain:@"domain" code:102 userInfo:[NSDictionary dictionaryWithObject:@"Invalid Quantity" forKey:NSLocalizedDescriptionKey]];
return NO;
}
return YES;
}
【问题讨论】:
-
据我了解,如果任何验证方法报告错误,
save:操作应该失败(并且不会向商店写入任何内容)。
标签: ios validation core-data kvc