gpt4 book ai didi

ios - 使用键值编码的核心数据验证

转载 作者:行者123 更新时间:2023-11-28 22:26:17 24 4
gpt4 key购买 nike

我创建了一个 Core Data 模型并创建了一个类别类,其中包含用于更新和删除数据的方法。我正在尝试向类中添加验证方法并尝试使用 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;
}

最佳答案

来自 the docs :

It is important to understand that how to validate is a model decision, when to validate is a user interface or controller-level decision (for example, a value binding for a text field might have its “validates immediately” option enabled).

还有:

There is nothing to disallow an in-memory object from becoming inconsistent on a temporary basis. The validation constraints are applied by Core Data only during a “save” operation or upon request (you can invoke the validation methods directly as and when you wish). Sometimes it may be useful to validate changes as soon as they are made and to report errors immediately.

请注意,当他们说“您可以直接调用验证方法”时,我不认为他们的意思是您实际上应该调用特定于属性的验证方法,因为在那之后有一条注释:

Important: If you do implement custom validation methods, you should typically not invoke them directly. Instead you should call validateValue:forKey:error: with the appropriate key. This ensures that any constraints defined in the managed object model are also applied.

因此,您的验证方法仅在保存上下文时才被调用这一事实不足为奇——那是 Core Data 进行验证的时候。也就是说,您可以更频繁地进行验证,如果您选择这样做,您应该通过调用 -validateValue:forKey:error: 来完成。

关于ios - 使用键值编码的核心数据验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18874110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com