NSManagedObject иерархия импорта и экспорта - PullRequest
4 голосов
/ 11 апреля 2011

Я в пути, чтобы сделать мой профиль NSMangedObjectClass импортируемым / экспортируемым.
Я пробую это таким образом
Экспорт работает правильно, если я пишу Связи в NSArrays, потому что NSSet не 'writeToFile реализовано.

- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
//Profile
NSMutableDictionary *profileDict = [[self.selectedProfile dictionaryWithValuesForKeys:[[[self.selectedProfile entity] attributesByName] allKeys]] mutableCopy];
NSMutableArray *views = [NSMutableArray array];

//Views
for (View *view in selectedProfile.views) {
    NSMutableDictionary *viewDict = [[view dictionaryWithValuesForKeys:[[[view entity] attributesByName] allKeys]] mutableCopy];
    NSMutableArray *controls = [NSMutableArray array];
         //Much more for-loops
    [viewDict setObject:controls forKey:@"controls"];
    [views addObject:viewDict];
}

[profileDict setObject:views forKey:@"views"];

if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES]) 
    NSLog(@"Saved");
else
    NSLog(@"Not saved");
[profileDict release];
}

Но если вы хотите импортировать на другую сторону

- (Profile*) importProfileFromPath:(NSString *)path{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
[newProfile setValuesForKeysWithDictionary:profileDict];
}

Я получаю исключение, меня это не смущает, потому что Profile ожидает NSSet и никакого NSArray.
[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException',<br> reason: '-[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0'
Итак, у меня есть две проблемы:

  • С одной стороны, я не могу записать NSSet в файл.
  • С другой стороны мояКласс профиля, ожидающий NSSet.

Поэтому я попытался создать категорию NSSet, которая реализует writeToFile

@implementation NSSet(Persistence)

- (BOOL)writeToFile:(NSString*)path atomically:(BOOL)flag{
    NSMutableArray *temp = [NSMutableArray arrayWithCapacity:self.count];
    for(id element in self)
        [temp addObject:element];
    return [temp writeToFile:path atomically:flag];
}

+ (id)setWithContentsOfFile:(NSString *)aPath{
    return [NSSet setWithArray:[NSArray arrayWithContentsOfFile:aPath]];
}
@end

Но мои функции не вызываются.

Есть ли другой способ написать мой NSSet или сказать setValuesForKeysWithDictionary, что ключ "views" - это NSArray?

Или простой способ импорта / экспорта ManagedObjects?

Ответы [ 2 ]

2 голосов
/ 12 апреля 2011

У меня проблемы с вложенным NSDictonarys, так что я попрощался с динамическим способом. Вот мое полное решение, чтобы помочь другим
ViewController для вызова функций im / export

- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
    //Call the NSManagedobject function to export
    NSDictionary *profileDict = [self.selectedProfile dictionaryForExport];

    if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES]) 
        NSLog(@"Saved");
    else
        NSLog(@"Not saved");
}

- (void) importProfileFromPath:(NSString *)path{
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];

    //load dictonary from file
    NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
    //call the NSManagedObjects import function
    [newProfile importWithDictonary:profileDict context:context];

    NSError *error = nil;
    if (![context save:&error]) {

        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

Функции NSManagedObject Я получил иерархию, поэтому я поместил их в каждый из моих NSManagedObjects

- (void) importWithDictonary:(NSDictionary*)dict context:(NSManagedObjectContext*)context{
    self.name = [dict objectForKey:@"name"];

    //Relationship
    for (NSDictionary *view in [dict objectForKey:@"views"]) {
        View *tempView = [NSEntityDescription insertNewObjectForEntityForName:@"View" inManagedObjectContext:context];
        [tempView importWithDictonary:view context:context];
        tempView.profile = self;
        [self addViewsObject:tempView];
    }
}

- (NSDictionary*) dictionaryForExport{ 
    //propertys
    NSMutableDictionary *dict = [[[self dictionaryWithValuesForKeys:[[[self entity] attributesByName] allKeys]] mutableCopy] autorelease];
    NSURL *objectID = [[self objectID] URIRepresentation];
    [dict setObject: [objectID absoluteString] forKey:@"objectID"];
    NSMutableArray *views = [NSMutableArray array];

    //relationship
    for (View *view in self.views) {
        [views addObject:[view dictionaryForExport]];
    }
    [dict setObject:views forKey:@"views"];
    return dict;
}

не самое красивое решение, но оно работает:)
и мне еще предстоит выяснить, как избежать дубликатов в моих отношениях n: m

Спасибо

1 голос
/ 11 апреля 2011

Вы можете попробовать переопределить реализацию по умолчанию для NSManagedObject setValuesForKeysWithDictionary?

Глядя на документацию , вам нужно только реализовать setValue: forKey: в ваших подклассах?

Вы должны быть в состоянии захватить NSSet и самостоятельно разобраться с ним до того, как возникнет исключение?

[Отказ от ответственности - я никогда не делал этого!]

...