读书人

IOS中的储存-Plist

发布时间: 2012-09-02 21:00:34 作者: rapoo

IOS中的存储-Plist

在Mac OS X的Cocoa,NeXTSTEP和GNUstep编程框架中,属性列表(Property List)文件是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist,因此通常被称为plist文件。

Plist文件通常用于储存用户设置,也可以用于存储捆绑的信息,该功能在旧式的Mac OS中是由资源分支提供的。

使用mac os 和Core Foundation中的property list接口我们可以在层式的对象和xml文件之间进行转换。我们可以把xml文件存储起来以后再把它以对象的形式读取出来。这里我们来具体讨论下property list和他们的表现形式,以及如何在编程过程中使用他们。

这里我想提到一下NSUserDefault,它其实也是以property list 的形式来存储的,但是它有限制,比如说NSColor和NSFont等类型式不能够直接存储的,我们必须要转换他们,要把他们转换成NSData类型来存储,我想在另一篇文章在详细说说这个问题。

废话不多说,我们开始吧。

在编程的过程中,我们可以在项目中建立plist来存储一些变量,具体的操作步骤File-new-Mac OS X-Resource-Property List。我们在项目中可以以xml形式或者source Code形式来编写。比如我们的plist原代码的形式象下面的xml一样。

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>    <key>Name</key>    <string>John Doe</string>    <key>Phones</key>    <array>        <string>408-974-0000</string>        <string>503-333-5555</string>    </array></dict></plist>
?

?

接下来我们从plist中读取信息,这是在iPhone开发中的应用:

 //get the plist file from bundle NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"]; // build the array from the plistNSMutableArray *anArray = [[NSMutableArray alloc]initWithContentOfFile:plistPath];

下面是写操作

    NSString *error;    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,                                     NSUserDomainMask, YES) objectAtIndex:0];    NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects:            [NSArray arrayWithObjects: personName, phoneNumbers, nil]            forKeys:[NSArray arrayWithObjects: @"Name", @"Phones", nil]];    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict                            format:NSPropertyListXMLFormat_v1_0                            errorDescription:&error];    if(plistData) {        [plistData writeToFile:plistPath atomically:YES];    }    else {        NSLog(error);        [error release];    }

?主要的内容来自于:

http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/PropertyLists/QuickStartPlist/QuickStartPlist.html#//apple_ref/doc/uid/10000048i-CH4-SW5

读书人网 >操作系统

热点推荐