ios开发学习-Plist文件

发布时间:2019-06-10 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ios开发学习-Plist文件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1、Plist 文件概述

直接将数据直接写在代码里面,不是一种合理的做法。如果数据经常改,就要经常翻开对应的代码进行修改, 造成代码扩展性低。

因此,可以考虑将经常变的数据放在文件中进行存储,程序启动后从文件中读取最新的数据。如果要变动数 据,直接修改数据文件即可,不用修改代码。

一般可以使用属性列表文件存储 NSArray 或者 NSDictionary 之类的数据,这种属性列表文件的扩展名是 plist, 因此也成为“Plist 文件”。

2、创建 Plist 文件

在创建 Plist 文件的时候要特别注意名称当中不能带“info”,如果带了“info”会导致 xcode 把它误当作一个项 目中某个文件而出现问题。,导致文件加载不进来。

ios开发学习-Plist文件

3、 解析Plist文件

(1)获得 Plist 文件的全路径

NSBundle *bundle = [NSBundle mainBundle];
NSString *path =
[bundle pathForResource:@"imageData(文件名)" ofTyPE:@"plist(扩展名)"];

(2)加载 plist 文件

//如果从网络加载可以用:
//_images = [NSArray arrayWIThContentsOfUrl:url];
 _images = [NSArray arrayWithContentsOfFile:path];
 - (NSArray *)images
{
  if (_images == nil)
  {
   //可以利用 mainBundle 获取手机里面的任何资
   NSBundle *bundle =  [NSBundle mainBundle];
   NSString *path =
[bundle pathForResource:@"imageData" ofType:@"plist"]; self.imageData = [NSArray arrayWithContentsOfFile:path];
 }

  return _images; 
}

打印项目所在Mac的路径:

// 获得项目的路径
NSBundle *bundle = [NSBundle mainBundle];
NSLOG(@"%@", bundle);

ios开发学习-Plist文件

获得项目目录下的plist文件路径

// 获得项目目录下的plist文件路径
 NSString *path = [bundle pathForResource:@"images" ofType:@"plist"];
    NSLog(@"%@", path);

ios开发学习-Plist文件

plist添加数据:
Root为数组类型,里边包含两个字典

ios开发学习-Plist文件

完整代码:

//
//  ViewController.m
//  02-plist学习
//
//  Created by kaiyi wang on 16/8/25.
//  Copyright © 2016年 Corwien. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    // 1.获得plist文件的全路径
    NSBundle *bundle = [NSBundle mainBundle];
    
    NSString *path = [bundle pathForResource:@"images" ofType:@"plist"];
    // NSLog(@"%@", path);
    
    NSArray *myPlist = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"%@", myPlist);   // 打印plist
    
    // NSNumber *num = @0;
    // 获取数组的第一个元素,字典类型
    NSDictionary *mydict = [myPlist objectAtIndex:0];   
    NSLog(@"%@", mydict[@"name"]);
    
}


@end

打印结果:

ios开发学习-Plist文件

是把 plist 文件转成一个 NSArray,里面存放各 Dictionary。以后可以根据索引从 dictArray 中取出对应 Dictionary, 再根据字段取出对应数据。

脚本宝典总结

以上是脚本宝典为你收集整理的ios开发学习-Plist文件全部内容,希望文章能够帮你解决ios开发学习-Plist文件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。