iosobjective-ccore-datansvaluetransformer

Cannot make transformedValue called in NSValueTransformer


There is my implementation of NSValueTransformer

+ (Class)transformedValueClass {
    return [NSData class];
}

+ (BOOL)allowsReverseTransformation {
    return YES;
}

- (id)transformedValue:(id)value {
    // some implementation, there is breakpoint
}

- (id)reverseTransformedValue:(id)value {
    // some implementation, there is breakpoint
}

I register it in runtime

 EncryptionTransformer *transformer = [[EncryptionTransformer alloc] init];
 [NSValueTransformer setValueTransformer:transformer forName:@"EncryptionTransformer"];

I mark my field as Transformable

enter image description here

And there is a property in my MO

@property (nonatomic, strong) NSData *someData;

@dynamic someData;

What am I doing wrong? transformedValue is not called.


Solution

  • I made some assumptions about your problem in comment above.. I reproduced your setup in test example and found following:

    1. Your setup is correct - and no need to setup value transformer in runtime like EncryptionTransformer *transformer = [[EncryptionTransformer alloc] init]; [NSValueTransformer setValueTransformer:transformer forName:@"EncryptionTransformer"];
    2. The actual value transformer's transformation method -(id)transformedValue: is called after -[NSManagedObjectContext save:]
    3. Moreover, if you NSManagedObjectContext isn't directly connected to persistent store coordinator (the popular approach provided out-of-box in frameworks like MagicalRecord or RestKit) -(id)transformedValue: isn't called after -[NSManagedObjectContext save:]. It is called only after -[NSManagedObjectContext save:] on context which is directly connected to persistent store coordinator.
    4. For the -(id)reverseTransformedValue:(id)value the similar rules are true - it is called only after fetches from persistent store coordinator

    Simple code (i use your setup):

    char *data = "abc";
    NSManagedObjectContext *moc =
    [(TCDAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
    Event *event = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Event class]) inManagedObjectContext:moc];
    event.timeStamp = [NSDate date];
    event.myData = [NSData dataWithBytes:data length:4];   // no call to -(id)transformedValue:
    [moc save:nil];   // called -(id)transformedValue: