plist文件

ios开发中经常会用到plist文件,其实就是xml文件,只是扩展名为.plist,NSArray或NSDictionary对象可以使用writeToFile:atomically:方法直接写入到Plist文件,可以将Plist文件内容直接加载至NSArray或NSDictionary,而无需XML解析

保存plist文件

 NSArray *document=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *dirdoc=document[0];
    //要写入的路径
    NSString *path=[dirdoc stringByAppendingString:@"info.plist"];
    
    //保存数组
    NSArray *array=@[_nameText.text,_telText.text,_ageText.text];
    [array writeToFile:path atomically:YES];
    
    //保存字典
    NSNumber *age=@(_ageText.text.intValue);
   // [NSNumber numberWithInteger:_ageText.text.integerValue];
    //保存dic
    NSDictionary *dic=@{@"name":_nameText.text,@"tel":_telText.text,@"age":age};
    NSString *dicPath=[dirdoc stringByAppendingString:@"dict.plist"];
    [dic writeToFile:dicPath atomically:YES];


读取plist文件

NSArray *docDir=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *doc=docDir[0];
    
    NSString *path=[doc stringByAppendingString:@"dict.plist"];
    NSDictionary *dic=[NSDictionary dictionaryWithContentsOfFile:path];
    _nameText.text=dic[@"name"];
    _telText.text=dic[@"tel"];
    _ageText.text=[dic[@"age"] stringValue];



注意:

•只有支持的数据类型可以被序列化,存储到plist中。无法将其他Cocoa对象存储到plist, 不能存储自定义对象
•支持的数据类型:
Array
Dictionary
Boolean
Date
Number
String

你可能感兴趣的:(IOS,高级)