gpt4 book ai didi

core-data - 如何从代码访问核心数据属性验证信息?

转载 作者:行者123 更新时间:2023-12-04 05:46:27 25 4
gpt4 key购买 nike

我在最大长度值为 40 的核心数据实体中有一个字符串属性。我想在代码中使用这个值,而不必重新键入值“40”。这可能吗?

最佳答案

正如@K.Steff 在上面的评论中所说,您最好在代码中进行验证,而不是在核心数据模型中设置最大长度。为了补充该评论,我还建议您考虑为此实体类型使用自定义 NSManagedObject 子类,并在该子类中覆盖 validateValue:forKey:error:或为此属性实现特定于 key 的验证方法。
这种方法的值(value)在于您可以通过在验证时截断字符串来执行诸如“强制”验证之类的操作。从 NSManagedObject 文档:

This method is responsible for two things: coercing the value into an appropriatetype for the object, and validating it according to the object’s rules.

The default implementation provided by NSManagedObject consults the object’s entitydescription to coerce the value and to check for basic errors, such as a null value whenthat isn’t allowed and the length of strings when a field width is specified for theattribute. It then searches for a method of the form validate< Key >:error: and invokes itif it exists.

You can implement methods of the form validate< Key >:error: to perform validation that isnot possible using the constraints available in the property description. If it finds anunacceptable value, your validation method should return NO and in error an NSError objectthat describes the problem. For more details, see “Model Object Validation”. Forinter-property validation (to check for combinations of values that are invalid), seevalidateForUpdate: and related methods.


因此,您可以实现此方法来验证字符串是否太长,并在必要时在字符串太长时将其截断。

关于core-data - 如何从代码访问核心数据属性验证信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10625702/

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