Objective-C arrayWithPlist(已经在NSString中)

Pat*_*cia 1 iphone objective-c plist nsstring nsarray

我有一个已包含pList的NSString.

我如何将其变成NSArray?(没有将其保存到磁盘,只能使用arrayWithContentsOfFile重新加载它,然后必须删除它.)

make arrayWithPlist或arrayWithString方法在哪里?(或者我将如何制作自己的?)

 NSArray *anArray = [NSArray arrayWithPlist:myPlistString];
Run Code Online (Sandbox Code Playgroud)

Jer*_*man 5

你想用NSPropertyListSerialization:

NSData *data = [plistString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSArray *plist = [NSPropertyListSerialization
                  propertyListWithData:plistData
                  options:/*unused*/0
                  format:NULL
                  error:&error];
if (!plist) {
    NSLog(@"%s: Failed to create plist: %@",
          __func__, error ?: @"(unknown error)");
}
Run Code Online (Sandbox Code Playgroud)

iOS 4.0/Mac OS X 10.6引入了这种特殊方法.在这些版本之前,您将使用:

NSData *data = [plistString dataUsingEncoding:NSUTF8StringEncoding];
NSString *errorText = nil;
NSArray *plist = [NSPropertyListSerialization
                  propertyListFromData:plistData
                  mutabilityOption:NSPropertyListImmutable
                  format:NULL
                  errorDescription:&errorText];
if (!plist) {
    NSLog(@"%s: Failed to create plist: %@",
          __func__, errorText ?: @"(unknown error)");

    /* Part of the reason this method was replaced:
     * It is the caller's responsibility to release the error description
     * if any is returned. This is completely counter-intuitive.
     */
    [errorText release], errorText = nil;
}
Run Code Online (Sandbox Code Playgroud)