Parse Plist (NSString) into NSDictionary

前端 未结 3 444
灰色年华
灰色年华 2020-11-27 15:52

So I have a plist structured string, that get dynamically (not from the file system). How would I convert this string to a NSDictionary.

I\'ve tried converting it N

相关标签:
3条回答
  • 2020-11-27 16:12

    See Serializing a Property List

    NSData* plistData = [source dataUsingEncoding:NSUTF8StringEncoding];
    NSString *error;
    NSPropertyListFormat format;
    NSDictionary* plist = [NSPropertyListSerialization propertyListWithData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
    NSLog( @"plist is %@", plist );
    if(!plist){
        NSLog(@"Error: %@",error);
        [error release];
    }
    
    0 讨论(0)
  • 2020-11-27 16:18

    I've tried converting it NSData and then to a NSDictionary with NSPropertyListSerialization, but it returns "[NSCFString objectAtIndex:]: unrecognized selector sent to instance 0x100539f40" when I attempt to access the NSDictionary, showing that my Dictionary was not successfully created.

    No, it shows no such thing. What it shows is that you tried to treat a string as an array. You'd need to determine where in the plist you were trying to get an array and why there was a string where you expected an array—i.e., whether you created the plist incorrectly (putting a string into it where you meant to put an array) or are examining it incorrectly (the presence of a string is correct; your subsequent expectation of an array is wrong).

    0 讨论(0)
  • 2020-11-27 16:37

    Try this:

    NSData * data = [yourString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    NSDictionary * dict = (NSDictionary*)[NSPropertyListSerialization
                                          propertyListFromData:data
                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];
    
    0 讨论(0)
提交回复
热议问题