Bolic
Bolic

Reputation: 745

Write Core Data to XML file

I am trying to write the data of core data to a xml file.

What is the best way? Using an arraycontroller which propably could provide the data?

Or try with NSFetchRequest? I tried the last but I think the output of the NSFecthRequest can not written to a xml file.

I used this code:

NSManagedObjectContext *moc = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"LanguageEntity" inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    [request setReturnsObjectsAsFaults:NO];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"1==1"];
    [request setPredicate:predicate];

    NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"language" ascending:YES];

    request.sortDescriptors = [NSArray arrayWithObject:descriptor];

    NSError *error;
    NSArray *array = [moc executeFetchRequest:request error:&error];
    NSLog(@"%@", array);
    if (array == nil)
    {
        NSLog(@"error");
    }
    else
    {
        NSString *root = @"/Users/Sebastian/Desktop/A6/A6/newPlist.xml";
        if (![[NSFileManager defaultManager]fileExistsAtPath:root])//checking fileexist or not
        {
            //if not exist creating the same
            [[NSFileManager defaultManager]createFileAtPath:root contents:nil attributes:nil];
            [[moc executeFetchRequest:request error:&error] writeToFile:root atomically:YES];
        }
        else
        {
            [[moc executeFetchRequest:request error:&error] writeToFile:root atomically:YES];
        }

    }

Is this mainly the correct way? Or should I use an ArrayController? And if so can you tell me please how to do?

Later I want to be able to save the core data content to an xml file and load an other xml or something particular.

Kind regards

Upvotes: 1

Views: 568

Answers (1)

Wain
Wain

Reputation: 119021

How you get the data is really beside the point. Your issue is with converting the data into a form which can be exported to XML and how you process that data.

By using:

[[moc executeFetchRequest:request error:&error] writeToFile:root atomically:YES];

(firstly you are re-executing a fetch that you have already executed) you are trying to directly convert an array of managed objects into XML (in a plist format). This isn't necessarily going to work because a plist has a very specific set of allowed data types, and managed objects aren't one of them.

You could change the fetch to return dictionaries (NSDictionaryResultType), and this would get you closer. But, any dates in the data you fetch would still cause it to fail. If you have any data types that can't be stored into a plist then you will need to perform a conversion into another data type before you try to convert the array.

Upvotes: 1

Related Questions