Why NSMutableDictionary don't want write to file?
Asked Answered
P

2

4
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([[NSFileManager defaultManager] fileExistsAtPath:pathString]) 
    {
        infoDict = [[NSMutableDictionary alloc] initWithContentsOfFile:pathString];
    } 
    else 
    {
        infoDict = [[NSMutableDictionary alloc]initWithObjects:[NSArray arrayWithObjects:@"BeginFrame",@"EndFrame", nil] forKeys:[NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithBool:YES], nil]];
        if ([infoDict writeToFile:pathString atomically:YES])
        {
            NSLog(@"Created");
        } 
        else 
        {
            NSLog(@"Is not created");
            NSLog(@"Path %@",pathString);
        }
}

This is my code. I check if file is created, if not - I create a NSMutableDictionary and I write it to file at path, but writeToFile method returns NO. Where is problem? If I create this file with NSFileManager it works, but doesn't when I want to write a dictionary.

Peculation answered 3/1, 2012 at 14:35 Comment(4)
Where does pathString come from?Facial
I said with [[NSFileManager defaultManager] createFileAtPath:pathString contents:nil attributes:nil]; this file was create...Peculation
i have first metode init and there I alloc itPeculation
it seems like you made a mistake initalizing the infoDict. I mean objects should be keys and keys- objects.Parnassus
B
29

writeToFile:atomically only works if the dictionary you call it on is a valid property list object (see docs).

For a NSDictionary to be a valid property list object, among other things, its keys must be strings, but in your example the keys are NSNumber instances.

Bowl answered 3/1, 2012 at 14:41 Comment(2)
thx... this is problem... but it worked fine in 2011... without problems :DPeculation
Thanks! I just got tripped up by the requirement that all the keys have to be strings.Furrier
G
12

You can not control the content you are going to write sometimes. For example, you can't avoid a null value when you are going to write a JSON object that is gotten from a server.

NSData is compatible with these "invalid" values, so converting NSArray or NSDictionary to NSData is an ideal way in these cases.

write:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:jsonObject];
[data writeToFile:path atomically:YES];

read:

NSData *data = [NSData dataWithContentsOfFile:path];
NSDictionary *jsonObject = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Garry answered 18/12, 2013 at 13:44 Comment(1)
Awesome. As mentioned above you may not always be able to serialise JSON. This works great with my JSON.Superannuation

© 2022 - 2024 — McMap. All rights reserved.