核心数据:自动修剪字符串属性

Fra*_*cis 4 core-data objective-c ios

对于我的核心数据NSManagedObject,我想确保任何NSString属性只包含已经修剪过的空格的字符串.

我知道我可以通过覆盖每个setter方法来实现这一点,如下所示:

- (void)setSomeProperty:(NSString *)someProperty
{
    someProperty = [someProperty stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ((!someProperty && !self.someProperty) || [someProperty isEqualToString:self.someProperty]) return;

    [self willChangeValueForKey:@"someProperty"];
    [self setPrimitiveValue:someProperty forKey:@"someProperty"];
    [self didChangeValueForKey:@"someProperty"];
}
Run Code Online (Sandbox Code Playgroud)

但是,这似乎需要编写很多代码,特别是因为我的托管对象可能具有相当多的NSString属性.

有没有更简单的方法?

Mar*_*ams 5

您可以NSValueTransformer为模型编辑器中的新变换器创建自定义NSString并将所有NSString属性分配给新变换器:

@interface StringTransformer: NSValueTransformer {}
@end

@implementation StringTransformer
+ (Class)transformedValueClass { 
  return [NSString class]; 
}

+ (BOOL)allowsReverseTransformation { 
    return YES;
}

- (id)transformedValue:(id)value {
    return value;
}

- (id)reverseTransformedValue:(id)value {
    return [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
Run Code Online (Sandbox Code Playgroud)