开发者

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

开发者 https://www.devze.com 2022-12-28 12:59 出处:网络
how to store values inside Plist 开发者_JAVA技巧and read while runtime in iphone 3.0?. Thanks in Advance.If you have an array or dictionary that contains only \"standard\" data types like strings, da

how to store values inside Plist 开发者_JAVA技巧and read while runtime in iphone 3.0?.

Thanks in Advance.


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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号