广

IOS开发

  • IOS开发
  • android开发
  • PHP编程
  • JavaScript
  • ASP.NET
  • ASP编程
  • JSP编程
  • Java编程
  • 易语言
  • Ruby编程
  • Perl编程
  • AJAX
  • 正则表达式
  • C语言
  • 编程开发

    iOS应用中存储用户设置的plist文件的创建与读写教程

    2018-04-06 10:40:47 次阅读 稿源:互联网
    广告

        在做iOS开发时,经常用到到plist文件,  那plist文件是什么呢? 它全名是:Property List,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,因此通常被称为 plist文件。文件是xml格式的。
    Plist文件通常用于储存用户设置,也可以用于存储捆绑的信息

    我们创建一个项目来学习plist文件的读写。

    1、创建项目Plistdemo
    项目创建之后可以找到项目对应的plist文件,打开如下图所示:

    在编辑器中显示类似与表格的形式,可以在plist上右键,用源码方式打开,就能看到plist文件的xml格式了。

    2、创建plist文件。
    按command +N快捷键创建,或者File —> New —> New File,选择Mac OS X下的Property List

    文件名为 customInfo,Group选择Supporting Files。

    3、单击新建的customInfo.plist,我们添加数据,如下图:

    注意,Type一项的类型,选择的是Dictionary,以Source Code打开,显示如下:

    <?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>Student</key> <dict> <key>Name</key> <string>Yang</string> <key>Sex</key> <string>Male</string> <key>Num</key> <string>SX_010</string> </dict> <key>Mentor</key> <dict> <key>Name</key> <string>Gu</string> <key>Sex</key> <string>Male</string> </dict></dict></plist>

    4、为视图添加控件:
    单击BIDViewController.xib,打开IB,拖几个控件上去,并设置好布局,如下图:

    上图中所有的控件都是Label,并设置了字体大小。

    5、接下来就是映射呗,把五个灰色的Label都映射到BIDViewController.h文件中,类型都是OutLet,名称依次是stuName,stuSex,stuNum,mtName,mtSex。

    6、单击BIDViewController.m,在viewDidLoad方法中的[super viewDidLoad]之后添加如下代码:
    代码如下:

    //首先读取studentInfo.plist中的数据
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"customInfo" ofType:@"plist"];
    NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
       
    //将学生信息填入视图
    NSDictionary *tmpInfo = [dictionary objectForKey: @"Student"];
    self.stuName.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Name"]];
    self.stuSex.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Sex"]];
    self.stuNum.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Num"]];
       
    //将导师信息写入视图
    tmpInfo = [dictionary objectForKey: @"Mentor"];
    self.mtName.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Name"]];
    self.mtSex.text = [NSString stringWithFormat:@"%@", [tmpInfo objectForKey: @"Sex"]];

    7、运行,查看效果:

    一起学吧部分文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与一起学吧进行文章共享合作。

    广告
    广告
    广告