Search code examples
iosnsarraynsdictionary

NSDictionary suddenly becomes an NSArray


I have this URL that returns JSON. I write the JSON to a Dictionary as follows:

NSData* Data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
NSDictionary *schools = [NSJSONSerialization JSONObjectWithData:Data options:kNilOptions error:nil];

Then, I write that Dictionary to a file:

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"schools.plist"];    
[schools writeToFile:filePath atomically:YES];

While running the code, I inspect the Dictionary, that appears to contain valid objects:

enter image description here

However, when I inspect the file on disk, it looks like an Array:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <dict>
        <key>Id</key>
        <string>ffefe0f7-23bf-471f-8e99-58ada0229921</string>
        <key>Name</key>

Is that expected behavior? Other methods in my code rely on getting a Dictionary from that file.


Solution

  • Just because you declare your variable to be of type NSDictionary does not mean that the call to JSONObjectWithData is really returning an NSDictionary.

    My guess is that the file you're getting from your server is really an array that contains a dictionary. Try logging the type of the object returned by JSONObjectWithData before you save it to a file:

    NSDictionary *schools = [NSJSONSerialization JSONObjectWithData:Data 
      options:kNilOptions error:nil];
    NSLog(@"schools class = %@", [schools class]);