2011-11-03 64 views
3

我想保存/写入一个数组到文档目录,我完全卡住了。我已经在线查看了多个源代码。我从NSArray切换到NSMutableArray,并没有奏效。从我可以告诉的是文件没有被写入,因为测试返回null。在此先感谢写一个NSArray到文件

NSArray *results = [parser objectWithData:data1]; 

NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:results]; 
// Create a dictionary from the JSON string 

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"EmployeeData.plist"]; 

//NSLog(@"the path is %@, the array is %@", path, array2); 

/////write to file///// 
[array2 writeToFile:path atomically:YES]; 

NSMutableArray *test = [[NSMutableArray alloc ]initWithContentsOfFile:path]; 

NSLog(@"the test is %@", test); 

**更新**

我添加几行代码

BOOL write = [results writeToFile:path atomically:YES]; 

NSLog(@"did it right? %@", write); 

,并写为空,这是什么意思?

这是我的数组

{ 
    0 = "<null>"; 
    1 = "John Doe"; 
    10 = 512; 
    11 = "<null>"; 
    12 = 1; 
    13 = 1; 
    2 = Doe; 
    3 = Jon; 
    4 = "<null>"; 
    5 = johndoe; 
    6 = "<null>"; 
    7 = "<null>"; 
    8 = "[email protected]"; 
    9 = "<null>"; 
    Type = 1; 
    Active = 1; 
    Depart = "<null>"; 
    Emp = "<null>"; 
    Ext = "<null>"; 
    FirstName = Jim; 
    Fl = 512; 
    Name = "John Doe"; 
    Log = jd; 
    Mobile = "<null>"; 
    Title = "<null>"; 
} 

的众多对象中的一个执行空值有什么关系呢?

已解决!

我意识到空值可能会导致一些问题,所以我改变了我的查询来照顾它,并立即保存。上面的代码是100%正确的,它的工作原理!

感谢您的帮助

+1

你可以欺骗并写入'[array2 description]'到文件中。 –

回答

16

按照该documentationwriteToFile:只适用,如果你的数组的内容仅限于类型(NSStringNSDataNSArray,或者NSDictionary对象)了一把。如果您的数组中有任何其他类型的对象,那么它将不会正确写入文件(或根本不写入)。

还要注意writeToFile:返回一个布尔值,指示操作是否成功。

如果你的数组包含不兼容的类型,你将不得不考虑使用类似NSKeyedArchiver的东西来序列化你的数据。

+0

我拥有的是一个解析网站的数组。我从JSON获得了数组中的信息。所以它是一个对象数组。你认为这与它无关吗? – zach

+0

是的,可能有些对象是不兼容的类型。你可以非常简单地通过执行如下操作来检查:'for(NSObject * obj in array){NSLog(“%@”,[obj class]); }'。请注意,如果您有复杂的JSON数据结构,那么您可能需要修改循环以通过嵌套数组和字典进行递归。 – aroth

+0

我刚刚在上面的描述中添加了我的一个对象 – zach