iosobjective-ccore-datacmtime

Trying to store CMTime as Transformable property on Core Data


I have used transformable properties of Core Data before but not with C objects like CMTime.

I need to store a CMTime on Core Data using transformable.

On the Model object I have declared this as transformable.

@property (nonatomic, retain) id tempo;

I understand that CMTime is a C object and I need to convert this to a NSDictionary and serialize it, so I can store on Core Data.

On the NSManagedObject class, I have this...

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

+(BOOL) allowsReverseTransformation
{
  return YES;
}

-(id)transformedValue:(id) value
{
  CFDictionaryRef dictTime = CMTimeCopyAsDictionary(?????, kCFAllocatorDefault);
  NSDictionary *dictionaryObject = [NSDictionary dictionaryWithDictionary:(__bridge NSDictionary * _Nonnull)(dictTime)];
  return [NSKeyedArchiver archivedDataWithRootObject:dictionaryObject];
}

-(id)reverseTransformedValue:(id)value
{
  // not complete ???
  return (NSDictionary*) [NSKeyedUnarchiver unarchiveObjectWithData:value];
}

The ????? is my problem. You see, the method transformedValue:(id)value receives value as id but I need a CMTime. I cannot simply cast it.

Also, when I create an instance of this entity, in theory I should be able to assign the value as this:

myEntity.tempo = myCmTimeValue;

and I am not seeing how I can do that to an id...

also, on reverseTransformedValue: I am returning an id.

I do not understand that. I want to be able to set and receive a CMTime


Solution

  • CMTime is a struct and NSValueTransformer can only be used with objects (pointers).

    A workaround is to wrap CMTime in NSValue

    @property (nonatomic, retain) NSValue *tempo;
    

    and convert NSValue to CMTime and vice versa

    CMTime time = [self.tempo CMTimeValue];
    
    
    self.tempo = [NSValue valueWithCMTime:time];