Common issues when calling writeToFile: atomically: on an NSDictionary object

0.00 avg. rating (0% score) - 0 votes

One of the easiest ways to convert an NSDictionary into a plist file is to use

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;

However, a common drawback of this method is that its execution sometimes simply returns NO upon failure without providing extra information, which makes it very hard for us to find out the root cause.

Below are some common reasons for this method to fail:

The path does not exist

There are several ways to check the existence of the folder where the file belongs to. I often prefer to use

- (BOOL)fileExistsAtPath:(NSString *)path;

and check if the path exists:

NSString *filePath = @".....";
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[filePath stringByDeletingLastPathComponent]]){
// parent folder exists
} else {
// something wrong with the path.
}

The NSDictionary object contains complex objects

To write into the file, make sure your dictionary contains only simple objects such as NSNumber, NSString, NSArray, … For complex objects such as CLBeacon; CLLocationManager, object, … the writing operation will fail because it doesn’t know how to properly format the data to be written.

For example, the following code will result in writeStatus being set to NO:

CLBeacon* beacon = ....
NSMutableDictionary* newDict = [[NSMutableDictionary alloc] init];
[newDict setObject:beacon.proximityUUID forKey:@"uuid"];
[newDict setObject:beacon.major forKey:@"major"];
[newDict setObject:beacon.minor forKey:@"minor"];
BOOL writeStatus = [currentCalibration writeToFile:filePath atomically:NO];

This is because beacon.beacon.proximityUUID is a customized object which is derived from NSObject, which writeToFile: atomically: does not know how to handle.

0.00 avg. rating (0% score) - 0 votes
ToughDev

ToughDev

A tough developer who likes to work on just about anything, from software development to electronics, and share his knowledge with the rest of the world.

Leave a Reply