Plist Array to NSDictionary

前端 未结 2 1456
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 14:53

I have a plist:


  
    
      name
      Alabama
          


        
相关标签:
2条回答
  • 2020-12-01 15:30

    The two problems:

    • Loading the plist into an NSDictionary:

    This is a simple problem, which it seems you have already figured out. The global object in your plist is an array, not a dict, so when you load it into the dictionary, it doesn't know what to do (incompatable types), so you're getting an empty dictionary.

    • Looping through the array of dictionaries:

    From the Exception you're getting, you are calling 'setObject:forKey:' on the dictionary, which is initialized as an NSDictionary, not an NSMutableDictionary. The pointer is typed as NSMutableDictionary, but not the actual in memory object. You need to change your line from.

    NSMutableDictionary *myDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    

    to

    NSMutableDictionary *myDic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    

    and actually, since loading the dictionary from the file gives you an empty dictionary, you are wasting cycles trying to load it from the file, and should just create a new one:

    NSMutableDictionary *myDic = [[NSMutableDictionary alloc] init];
    
    0 讨论(0)
  • 2020-12-01 15:40

    A more flexible way to load plists into memory, that also allows you to create mutable plists:

    NSData* data = [NSData dataWithContentsOfFile:path];
    NSMutableArray* plist = [NSPropertyListSerialization propertyListFromData:data
                                                             mutabilityOption:NSPropertyListImmutable
                                                                       format:NSPropertyListXMLFormat_v1_0
                                                             errorDescription:NULL];
    

    Thus your code could be implemented as:

    NSString *path = [[NSBundle mainBundle] pathForResource:@"stateInfo" ofType:@"plist"];
    NSData* data = [NSData dataWithContentsOfFile:path];
    NSMutableArray* array = [NSPropertyListSerialization propertyListFromData:data
                                                             mutabilityOption:NSPropertyListImmutable
                                                                       format:NSPropertyListXMLFormat_v1_0
                                                             errorDescription:NULL];
    if (array) {
      NSMutableDictionary* myDict = [NSMutableDictionary dictionaryWithCapacity:[array count]];
      for (NSDictionary* dict in array) {
        State* state = [[State alloc] initWithDictionary:dict];
        [myDict setObject:state forKey:state.name;
        [state release];
      }
      NSLog(@"The count: %i", [myDic count]);
    } else {
      NSLog(@"Plist does not exist");
    }
    
    0 讨论(0)
提交回复
热议问题