简体   繁体   English

获取NSManagedObject属性验证正则表达式

[英]Get NSManagedObject attribute validation regular expression

In my data model, some of the attributes have regular expressions used for data validation. 在我的数据模型中,一些属性具有用于数据验证的正则表达式。 There are places in my code that I would like to use those same regular expressions. 我的代码中有些地方我想使用那些相同的正则表达式。

In the interest of keeping my common regular expressions in one place, I was hoping either to set these regexes in code or to retrieve them from the data model in code. 为了将我的常用正则表达式保存在一个地方,我希望在代码中设置这些正则表达式或者从代码中的数据模型中检索它们。

Is there a way to do this? 有没有办法做到这一点?

I want to access the Reg. 我想访问Reg。 Ex. 防爆。 property, shown below, in code. 属性,如下所示,代码。

我想访问Reg。防爆。代码中的属性

From a NSEntityDescription you can get its attributes with the method attributesByName . NSEntityDescription您可以使用方法attributesByName获取其attributesByName Then you can use the NSPropertyDescription methods validationPredicates and setValidationPredicates:withValidationWarnings: . 然后,您可以使用NSPropertyDescription方法validationPredicatessetValidationPredicates:withValidationWarnings: . I assume that a predicate is created under the hood when you set the validation regex in your datamodel file... 我假设在您的datamodel文件中设置验证正则表达式时会在引擎盖下创建谓词...

I am not completely sure about this, but I think you can only set these values when you are creating your core data model, not once you have your core data stack set up. 我对此并不完全确定,但我认为您只能在创建核心数据模型时设置这些值,而不是在设置核心数据堆栈后设置这些值。 Is that what you want to do? 那是你想做的吗?

Absolutely. 绝对。 Everything you do in the model editor can be done or modified in code by manipulating your NSManagedObjectModel object. 您可以通过操作NSManagedObjectModel对象在代码中完成或修改模型编辑器中的所有操作。

Locate where the model is retrieved in your core data stack setup (maybe in your app delegate). 找到核心数据堆栈设置中检索模型的位置(可能在您的应用程序委托中)。 Before returning the model, modify it in code, using constants you can #define in a central include file. 在返回模型之前,在代码中修改它,使用常量#define在中心包含文件中。

Read all about the object model's API here . 在这里阅读有关对象模型的所有API。 More precisely, you set the model's entities after modifying an entity description, by changing the validationPredicates of one of its attributes . 更准确地说,您可以在修改实体描述后通过更改其attributesvalidationPredicates来设置模型的entities

I marked e1985's answer as accepted, since that's the answer that led me here. 我将e1985的答案标记为已被接受,因为这是我的答案。 Here's the code I used to get the predicate. 这是我用来获取谓词的代码。 It's in a category for NSEntityDescription. 它属于NSEntityDescription的类别。

- (NSPredicate*)getValidationPredicateForAttribute:(NSString*)attributeName
{
    NSAttributeDescription* emailAttribute = [self.attributesByName objectForKey:attributeName];
    NSArray* validationPredicates = [emailAttribute validationPredicates];

    if(validationPredicates.count > 0)
    {
        return [validationPredicates objectAtIndex:0];
    }

    return nil;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM