2016-08-02 16 views
0

からStringに1つの属性タイプを変更するには、NSEntityMigrationPolicycreateDestinationInstancesForSourceInstanceメソッドを使用します。ただし、既存のオブジェクトを置き換えるのではなく、新しいオブジェクトを作成します。ここでNSEntityMigrationPolicyは、既存の変更の代わりに新しいオブジェクトを作成します

は私のコードです:

#import "MessageTransformationPolicy.h" 

@implementation MessageTransformationPolicy 

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance 
             entityMapping:(NSEntityMapping *)mapping 
              manager:(NSMigrationManager *)manager 
               error:(NSError **)error 
{ 
    // Create a new object for the model context 
    NSManagedObject *newObject = 
    [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName] 
            inManagedObjectContext:[manager destinationContext]]; 

    // do our transfer of nsdate to nsstring 
    NSData *messageMetadata_dataType = [sInstance valueForKey:@"metadata"]; 
    NSString *messageMetadata_stringType = [[NSString alloc] initWithData:messageMetadata_dataType encoding:NSUTF8StringEncoding]; 

    // set the value for our new object 
    [newObject setValue:messageMetadata_stringType forKey:@"metadata"]; 

    // do the coupling of old and new 
    [manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping]; 

    return YES; 
} 

@end 

どこに問題がありますか?問題が解決し、Msgという名前のターゲットエンティティのすべての属性を保存し、保存する方法を変更することにより、

答えて

0

- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)inSourceInstance 
             entityMapping:(NSEntityMapping *)inMapping 
              manager:(NSMigrationManager *)inManager 
               error:(NSError **)outError { 
    NSManagedObject *newObject; 
    NSEntityDescription *sourceInstanceEntity = [inSourceInstance entity]; 

    // sure to have the right entity 
    if ([[sourceInstanceEntity name] isEqualToString:@"Msg"]) { 
     newObject = [NSEntityDescription insertNewObjectForEntityForName:@"Msg" inManagedObjectContext:[inManager destinationContext]]; 

     // get the attributes 
     NSDictionary *keyValDict = [inSourceInstance committedValuesForKeys:nil]; 
     NSArray *allKeys = [[[inSourceInstance entity] attributesByName] allKeys]; 
     // loop over the attributes 
     for (NSString *key in allKeys) { 
      // Get key and value 
      id value = [keyValDict objectForKey:key]; 
      if ([key isEqualToString:@"metadata"]) {     
       NSData *messageMetadata_dataType = [keyValDict valueForKey:@"metadata"]; 
       NSString *messageMetadata_stringType = [[NSString alloc] initWithData:messageMetadata_dataType encoding:NSUTF8StringEncoding]; 

       [newObject setValue:messageMetadata_stringType forKey:key]; 
      } else { 
       [newObject setValue:value forKey:key]; 
      } 
     } 

     [inManager associateSourceInstance:inSourceInstance withDestinationInstance:newObject forEntityMapping:inMapping]; 
    } 
    return YES; 
} 
関連する問題