Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: Automatically Trim String Properties

For my Core Data NSManagedObject, I would like to ensure any NSString properties only contain strings that have been trimmed of whitespace.

I'm aware that I could achieve this by overriding each setter method, like so:

- (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"];
}

However, this seems like a lot of code to have to write, especially since my managed object is likely to have quite a few NSString properties.

Is there an easier way?

like image 276
Francis Avatar asked Feb 15 '23 12:02

Francis


1 Answers

You could create a custom NSValueTransformer for NSString and assign all of your NSString properties to the new transformer in the model editor:

@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
like image 190
Marcus Adams Avatar answered Feb 23 '23 05:02

Marcus Adams