Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary writeToFile fails while objects are valid, permission is 0k

Why NSDictionary cannot be written?? I have checked the content of the dictionary: all the instances are of NSString and NSNumber. I checked permissions: a text file with the same name at the same path is written well. Of course, my dictionary is not empty.

NSString *file = ...
NSDictionary *dict = ...

// check dictionary keys
BOOL wrong = NO;
for (id num in [dict allKeys]) {
    if (![num isKindOfClass:[NSNumber class]]) {
        wrong = YES;
        break;
    }
}
if (wrong) {
    NSLog(@"First");
}
// check dictionary values
wrong = NO;
for (id num in [dict allValues]) {
    if (![num isKindOfClass:[NSString class]]) {
        wrong = YES;
        break;
    }
}
if (wrong) {
    NSLog(@"Second");
}

if (![dict writeToFile:file atomically:YES]) {
    // 0k, let's try to create a text file
    NSLog(@"Names writing error!");
    [@"Something here... .. ." writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

Output: "Names writing error!"
Text file is created successfully.

like image 846
AivanF. Avatar asked Mar 13 '23 02:03

AivanF.


1 Answers

Writing out a dictionary creates a property list, and according to the documentation all keys in a property list must be strings.

... and although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

NSNumber objects as keys are not supported.

like image 196
vadian Avatar answered Apr 09 '23 12:04

vadian