Thursday, May 9, 2013

NSDictionary writeToFile atomically example ios

writeToFile atomically

Writes a property list representation of the contents of the dictionary to a given path.
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
The path at which to write the file.
If path contains a tilde (~) character, you must expand it withstringByExpandingTildeInPath before invoking this method.
flag ([NSDictionary writeToFile atomically])
A flag that specifies whether the file should be written atomically.
If flag is YES, the dictionary is written to an auxiliary file, and then the auxiliary file is renamed to path. If flag is NO, the dictionary 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
YES if the file is written successfully, otherwise NO.
Discussion of [NSDictionary writeToFile atomically]
This method recursively validates that all the contained objects are property list objects (instances of NSDataNSDateNSNumberNSStringNSArray, or NSDictionary) 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. [NSDictionary writeToFile atomically]
If the dictionary’s contents are all property list objects, the file written by this method can be used to initialize a new dictionary with the class method dictionaryWithContentsOfFile:or the instance method initWithContentsOfFile:.
For more information about property lists, see Property List Programming Guide.
Example of [NSDictionary writeToFile atomically]
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"myPlistFile.plist"];
if (![fileManager fileExistsAtPath: path])
          NSString *bundle = [[NSBundle mainBundle] pathForResource:@”myPlistFile ofType:@”plist”];
          [fileManager copyItemAtPath:bundle toPath:path error:&error];
[myDict writeToFile:plistPath atomically: YES];
Example of [NSDictionary writeToFile atomically]
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistDirectory = [paths objectAtIndex:0];
NSString *plistPath = [plistDirectory stringByAppendingPathComponent:@"userCompany.plist"];

NSArray *userObjects = [[NSArray alloc] initWithObjects:@"Joe", @"Smith", @"Smith Co", nil];
NSArray *userKeys = [[NSArray alloc] initWithObjects:@"First Name", @"Last Name", @"Company", nil];

NSDictionary *userSettings = [[NSDictionary alloc] initWithObjects:userObjects forKeys:userKeys];

[userSettings writeToFile:plistPath atomically:YES];