views:

46

answers:

1

I have an NSString that already contains a pList.

How do I turn it into an NSArray? (WITHOUT saving it to disk, only to reload it back with arrayWithContentsOfFile, and then have to delete it.)

Where is the make arrayWithPlist or arrayWithString method? (Or how would I make my own?)

 NSArray *anArray = [NSArray arrayWithPlist:myPlistString];
+4  A: 

You want to use 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)");
}

That particular method was introduced with iOS 4.0/Mac OS X 10.6. Prior to those releases, you would use:

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;
}
Jeremy W. Sherman
I'll give that a try. I guess the BIG question is: How would I have figured that out on my own? I would have NEVER have thought to look deep inside NSPropertyListSerialization for this solution.
Patricia
You want to do something with property lists. So, in the Xcode documentation window, you would start typing "property". Then you might find that class, or you would find and read Apple's [Property List Programming Guide](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/PropertyLists/Introduction/Introduction.html). Apple's documentation is really very good, and they provide a lot of sample code and projects, too.
Jeremy W. Sherman