2014-06-09 133 views
1

我正在尝试将核心数据的数据写入xml文件。将核心数据写入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或特定的东西。

亲切的问候

回答

1

你如何获得数据真的是无关紧要的。您的问题是将数据转换为可导出到XML的表单,以及如何处理该数据。

使用:

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

(首先您要重新执行抓取您已经执行)你想直接将管理对象的数组到XML(中的plist格式)。这不一定会奏效,因为plist有一组非常特定的允许数据类型,而管理对象不是其中之一。

您可以更改提取返回字典(NSDictionaryResultType),这会让你更接近。但是,您获取的数据中的任何日期仍然会导致失败。如果您有任何数据类型无法存储到plist中,则在尝试转换数组之前,您需要执行到另一种数据类型的转换。

+0

Wain?你拯救了我的一天。我实际上是在寻找像setResultType这样的东西!如果我在那里设置NSDictionaryResultType并将其保存在xml文件中,一切都完成了。 – Bolic