Saturday, June 1, 2013

NSArray writeToFile example in Objective C (iOS).

NSArray writeToFile

Writes the contents of the array to a file at a given path.

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Parameters of [NSArray writeToFile]
The path at which to write the contents of the array.
If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
If YES, the array is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Return Value of [NSArray writeToFile]
YES if the file is written successfully, otherwise NO.

Discussion of [NSArray writeToFile]
If the array’s contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

NSArray writeToFile example.
//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];

//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
    //Array file didn't exist... create a new one
    yourArray = [[NSMutableArray alloc] initWithCapacity:10];

    //Fill with default values
//Use the content
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];

Example of [NSArray writeToFile].
if(![array containsObject:dictionary])
[array addObject:dictionary];
if(![array writeToFile:path atomically:YES])
NSLog(@".plist writing was unsucessfull");

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

MyClass * myObject = [[MyClass alloc] init];
NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:myObject];
[array writeToFile:issueURLsPlist atomically:YES];

End of NSArray writeToFile example article.