美文网首页日志系统(iOS 文件存储)
iOS持久化存储之Plist文件

iOS持久化存储之Plist文件

作者: kingandyoga | 来源:发表于2016-05-21 15:45 被阅读367次

    plist

    创建plist文件(xml)

    在Xcode里面,我们创建一个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里面看到。


    用代码创建plist文件

    plise文件中的数据属性必须是下面这些:

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

    ** 代码1: **创建一个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 {
            // 没有不存在这个文件,那么创建一个空的字典
            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

    相关文章

      网友评论

        本文标题:iOS持久化存储之Plist文件

        本文链接:https://www.haomeiwen.com/subject/ngxorttx.html