Search code examples
objective-cnsmutabledictionarywritetofile

NSMutableDictionary not saving to local directory


I test to see if a directory is saving and it doesn't seem that it is.

Here is what I have, it's essentially creating a list of which files have been uploaded to Dropbox. DropboxList is declared in the header file and then synchronized.

int i = 0;

DropboxList = [[NSMutableDictionary alloc]init];

do {

[DropboxList setObject:@"NO" forKey:[NSNumber numberWithInt:i]];

i++;

} while (i < sortedFiles.count);

NSLog(@"dropbox list is %@", DropboxList);


NSArray *dropBoxPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dropBoxDocumentsDirectory = [dropBoxPaths objectAtIndex:0];
NSString *dropBoxDataPath = [dropBoxDocumentsDirectory stringByAppendingPathComponent:@"/DropboxUploads"];

if (![[NSFileManager defaultManager] fileExistsAtPath:dropBoxDataPath]) {
    [[NSFileManager defaultManager] createDirectoryAtPath:dropBoxDataPath withIntermediateDirectories:NO attributes:nil error:nil];
}

NSString *filePath = [dropBoxDataPath stringByAppendingPathComponent:@"dropboxList.out"];

[DropboxList writeToFile:filePath atomically:YES];

NSMutableDictionary *newDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];

NSLog(@"newDictionary list is %@", newDictionary);

Here is my console:

dropbox list is {
    0 = NO;
    3 = NO;
    2 = NO;
    1 = NO;
    4 = NO;
}
newDictionary list is (null)

I've tried alloc init for the newDictionary before writing and I get the same result. Any ideas?


Solution

  • The problem is with the following line

    [DropboxList setObject:@"NO" forKey:[NSNumber numberWithInt:i]];
    

    DropboxList writeToFile only works with the valid property list. For a NSMutableDictionary to be a valid property list object, its keys should be string type instead of NSNumber.

    Solution

    [DropboxList setObject:@"NO" forKey:[NSString stringWithFormat:@"%d",i]]];
    

    Also, make use of the writeToFile return parameter to validate.

    BOOL isWritten = [DropboxList writeToFile:filePath atomically:YES];
    if (isWritten)
    {
        NSMutableDictionary *newDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
        NSLog(@"newDictionary list is %@", newDictionary); 
    {
    else
    {
        NSLog(@"Something went wrong");
    }