iOS plist文件增删改查

一. plist简介
  • plist文件,即属性列表文件,全名是Property List,这种文件的扩展名为.plist,因此,通常被叫做plist文件。它是一种用来存储串行化后的对象的文件,在iOS开发中通常用来存储用户设置,还可以用于存储程序中经常用到而不经常改动的数据。下面就看一下如何创建和读写plist文件。
  • plist 只能存储基本的数据类型 和 array 字典

二. 首先是使用xcode自带的功能使用plist
1. 根据图片的顺序创建一个新的plist文件
2. 给plist命名
  • 需要注意的问题
    • 命名的时候不能用Info.plist , INfo.plist, xxxInfo.plist等形式,否则会出现下面的情况,因为系统中存在一个Info.plist文件,会发生冲突
3. 然后就可以在xcode中编辑plist文件了
4. 使用plist文件
  • 这里一般只能在读取plist文件,具体获取plist文件路径的代码为:

    复制代码
      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"newsModel" ofType:@"plist"];
  • 然后是获取plist里面的数据,这里跟下面是相同的


三. 使用代码的方式使用plist
1. 写入plist代码演示
复制代码
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [path objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"newsTest.plist"];
    //创建数据
    NSMutableDictionary *newsDict = [NSMutableDictionary dictionary];
    //赋值
    [newsDict setObject:@"zhangsan" forKey:@"name"];
    [newsDict setObject:@"12" forKey:@"age"];
    [newsDict setObject:@"man" forKey:@"sex"];
    //数据写入plist
    [newsDict writeToFile:plistPath atomically:YES];
2. 读取plist文件代码演示
复制代码
    //获取plist文件的路径
    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path1 = [pathArray objectAtIndex:0];
    NSString *myPath = [path1 stringByAppendingPathComponent:@"newsTest.plist"];

    //根据之前保存的容器类型读取数据
    //是数组就用数组来获取数据,是字典就用字典来获取数据
    //newsModel.plist文件
    //NSMutableArray *data1 = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
    //newsTest.plist文件
    NSMutableDictionary *data2 = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
3. plist的增删操作
  • 增删操作就是对读取后的plist数据容器进行的增删,然后保存就好
相关推荐
2501_9159214312 小时前
iOS 是开源的吗?苹果系统的封闭与开放边界全解析(含开发与开心上架(Appuploader)实战)
android·ios·小程序·uni-app·开源·iphone·webview
2501_9159090616 小时前
原生 iOS 开发全流程实战,Swift 技术栈、工程结构、自动化上传与上架发布指南
android·ios·小程序·uni-app·自动化·iphone·swift
2501_9151063216 小时前
Comodo HTTPS 在工程中的部署与排查实战(证书链、兼容性与真机抓包策略)
网络协议·http·ios·小程序·https·uni-app·iphone
2501_9159090616 小时前
苹果软件混淆与 iOS 代码加固趋势,IPA 加密、应用防反编译与无源码保护的工程化演进
android·ios·小程序·https·uni-app·iphone·webview
2501_9160074716 小时前
苹果软件混淆与 iOS 应用加固实录,从被逆向到 IPA 文件防反编译与无源码混淆解决方案
android·ios·小程序·https·uni-app·iphone·webview
Zender Han21 小时前
Flutter 实现人脸检测 — 使用 google_mlkit_face_detection
android·flutter·ios
2501_916008891 天前
iOS 26 性能分析深度指南 包含帧率、渲染、资源瓶颈与 KeyMob 协助策略
android·macos·ios·小程序·uni-app·cocoa·iphone
Mr_zheng1 天前
iOS 26 UIKit和Swift上的更新
ios·swift
YungFan1 天前
iOS26适配指南之UISearchController
ios·swift
陈彬技术实践1 天前
从 Auto Layout 原理看:为什么 UITableView.tableHeaderView 无法自动撑开?
ios