views:

336

answers:

2

Hi Guys,

how to store values inside Plist and read while runtime in iphone 3.0?.

Thanks in Advance.

+2  A: 

If you have an array or dictionary that contains only "standard" data types like strings, dates, numbers, arrays, and dictionaries, you can save the contents to a .plist file with -[NSArray writeToFile:atomically:] or -[NSDictionary writeToFile:atomically:]. To read the file, use -initWithContentsOfFile:.

Note that the application bundle is not writable on iPhone OS devices so you will have to store the file in your app's Documents directory.

Ole Begemann
+1  A: 

This solution can be applied to both NSArray and NSDictionary.

Use this method to make a NSData from property list and use writeToFile to persist it to disk.

[NSPropertyListSerialization dataFromPropertyList:(id)plist
                                           format:(NSPropertyListFormat)format
                                 errorDescription:(NSString **)errorString];

Use this method to read property list from NSData.

[NSPropertyListSerialization propertyListFromData:(NSData *)data
                                 mutabilityOption:(NSPropertyListMutabilityOptions)opt
                                           format:(NSPropertyListFormat *)format
                                 errorDescription:(NSString **)errorString];

Example:

NSPropertyListFormat format = 0;
NSString *errorString = nil;

NSDictionary *dataDict = [NSPropertyListSerialization propertyListFromData:data
        mutabilityOption:NSPropertyListMutableContainersAndLeaves
        format:&format errorDescription:&errorString];

if (errorString != nil) {
    NSLog(errorString);
    [errorString release];
}

NSLog(@"got dictionary:%@", dataDict);

errorString = nil;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:dataDict
        format:NSPropertyListXMLFormat_v1_0 errorDescription:errorString];

NSLog(@"plist data:%@", data); // convert to NSString to get <plist>
iwat