iOS持久化存儲之Plist文件

plist

創(chuàng)建plist文件(xml)

在Xcode里面,我們創(chuàng)建一個Cocoa項目(PlistTest)。之后cmd + n 新建文件,在Resourse里面選擇 Property List,并命名為 Data.plist

之后可以直接在plist文件里面添加項目。

因為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>李金</string>
    <key>Phones</key>
    <array>
        <string>123456</string>
        <string>234567</string>
    </array>
</dict>
</plist>

因為我們把plist文件放在了沙盒的資源目錄下,當應用啟動的時候,這個文件會被寫到 main bundle 里面。


代碼部分

  1. plist文件讀取
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath ;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

plistPath = [rootPath stringByAppendingPathComponent:@"Data.plist"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
        plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
   }
    NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
    NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization
                                          propertyListFromData:plistXML
                                          mutabilityOption:NSPropertyListMutableContainersAndLeaves
                                          format:&format
                                          errorDescription:&errorDesc];
    if (!temp) {
        NSLog(@"Error reading plist: %@, format: %lu", errorDesc, (unsigned long)format);
    }
    self.personName = [temp objectForKey:@"Name"];
    self.phoneNumbers = [NSMutableArray arrayWithArray:[temp objectForKey:@"Phones"]];

  1. plist文件寫入
NSArray *name = @[@"李1",@"李2",@"李3",@"李4",@"李5",@"李6"];
    personName = [name objectAtIndex:rand()%5];
    
    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");
    }

具體代碼可以在github里面看到。


用代碼創(chuàng)建plist文件

plise文件中的數據屬性必須是下面這些:

  • NSDictionary
  • NSArrat
  • NSString
  • NSDate
  • NSData
  • NSNumber

** 代碼1: **創(chuàng)建一個plist文件,一個NSDictionary對象(根對象),并加入一個數字;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"plist.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSMutableDictionary *data;
    
    if ([fileManager fileExistsAtPath: path]) {
        data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    }
    else {
        // 沒有不存在這個文件,那么創(chuàng)建一個空的字典
        data = [[NSMutableDictionary alloc] init];
    }
    
    //插入數據
    data[@"value"] = @(5);
    [data writeToFile: path atomically:YES];
    
    //讀取數據
    NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
    int value1;
    value1 = [savedStock[@"value"] intValue];
    NSLog(@"%i",value1);

參考資料:

[1] Apple Dev Library

[2] Stackoverflow Q&A

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容