我正在尝试将核心数据的数据写入xml文件。
最好的方法是什么?使用可以提供数据的数组控制器?
或尝试使用NSFetchRequest?我尝试了最后一个,但我认为NSFecthRequest的输出无法写入xml文件。
我使用了这段代码:
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];
}
}
这主要是正确的方法吗?或者我应该使用ArrayController?如果是这样,你能告诉我该怎么做?
稍后我希望能够将核心数据内容保存到xml文件并加载其他xml或特定内容。
亲切的问候
答案 0 :(得分:1)
如何获取数据真的不是重点。您的问题是将数据转换为可导出为XML的表单以及处理该数据的方式。
使用:
[[moc executeFetchRequest:request error:&error] writeToFile:root atomically:YES];
(首先,您正在重新执行已执行的提取)您正在尝试将托管对象数组直接转换为XML(以plist格式)。这不一定能够正常工作,因为plist具有一组非常特定的允许数据类型,而托管对象不是其中之一。
您可以更改提取以返回词典(NSDictionaryResultType
),这会让您更接近。但是,您获取的数据中的任何日期仍会导致其失败。如果您有任何无法存储到plist中的数据类型,那么在尝试转换数组之前,您需要先转换为另一种数据类型。