问题
I am trying to save/write an Array to the documents directory, and I am completely stuck. I have checked this code with multiple sources online. I switched from and NSArray to a NSMutableArray and that didn't work. From what I can tell is the file isn't being written, because test is coming back null. Thanks in advance
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);
** update **
I added these lines of code
BOOL write = [results writeToFile:path atomically:YES];
NSLog(@"did it right? %@", write);
and write is null, what does that mean?
This is one of the many objects in my Array
{
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 = "john@doe.com";
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>";
}
Do the null values have anything to do with it?
SOLVED!!
I realized that the null values may have been causing some issues, so i changed my query to take care of that and it saved instantly. The above code is 100% correct and it works!
thanks for the help
回答1:
As per the documentation, writeToFile:
only works if your array's contents are limited to a handful of types (NSString
, NSData
, NSArray
, or NSDictionary
objects). If you have any other type of object in your array, then it will not write to file correctly (or at all).
Note also that writeToFile:
returns a boolean value indicating whether or not the operation succeeded.
If your array contains incompatible types, you will have to look at using something like NSKeyedArchiver to serialize your data instead.
来源:https://stackoverflow.com/questions/8003244/writing-a-nsarray-to-file