iOS中plist的创建,数据写入与读取 !

功能创建一个test.plist文件,textInput作为输入,displayLabel作为显示,有一个按钮来触发保持程序triggerStorage;


-(void)triggerStorage

{

displayLabel.text = textInput.text;

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *path=[paths    objectAtIndex:0];

NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];   //获取路径

NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];  //读取数据

NSLog(@"dic2 is:%@",dic2);

//创建一个dic,写到plist文件里

NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:displayLabel.text,@"IP",nil]; //写入数据

[dic writeToFile:filename atomically:YES];

}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidLoad

{

NSMutableArray *resultData;

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString *path=[paths objectAtIndex:0];

NSLog(@"path = %@",path);

NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];

//读文件

NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];

NSLog(@"dic is:%@",dic2);

if(dic2 == nil)

{

//1. 创建一个plist文件

NSFileManager* fm = [NSFileManager defaultManager];

[fm createFileAtPath:filename contents:nil attributes:nil];

}

else

{

resultData=[dic2 objectForKey:@"IP"];

if([dic2 count] > 0)

{

displayLabel.text = resultData;

}

else

{

displayLabel.text = @" ";

}

}

self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]   //按钮的初始化及触发条件设置

initWithTitle:@"保存"

style:UIBarButtonItemStylePlain

target:self

action:@selector(triggerStorage)] autorelease];

[super viewDidLoad];

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,027评论 19 139
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • 《裕语言》速成开发手册3.0 官方用户交流:iApp开发交流(1) 239547050iApp开发交流(2) 10...
    叶染柒丶阅读 27,926评论 5 19
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,242评论 2 33
  • 在这个提笔忘字的时代,在这泯灭一切的似水流年里,是否还能记起书写的感觉,手指划过纸张的触感,心中流淌情感,思绪萦...
    不沸腾孩子阅读 66评论 0 0