一、 能够储存的类型
存储在plist中的数据是经过序列化的,虽然大多数类型都能被序列化,但是却不是所有的都能够存储到plist中,以下是可以储存的数据类型:
NSArray
NSMutableArray
NSDictionary
NSMutableDictionary
NSData
NSMutableData
NSString
NSMutableString
NSNumber
NSDate
不能储存的数据类型:
UIImage
UIColor
NSURL
二、存储plist
我们看下面一个例子:
点击“保存”能够实现把姓名和学号保存plist中,点击“清除”能够清除输入的数据,点击“读取”能够从plist中读取数据并显示在输入框内。
YGViewController.h
#import <UIKit/UIKit.h> @interface YGViewController : UIViewController @property (retain, nonatomic) IBOutlet UITextField *nameField;//姓名输入框 @property (retain, nonatomic) IBOutlet UITextField *stuNumField;//学号输入框 - (IBAction)saveInfo:(id)sender;//储存方法 - (IBAction)loadInfo:(id)sender;//清除方法 - (IBAction)clearInfo:(id)sender;//读取方法 @end
YGViewController.m
//获得文件路径 -(NSString *)filePath{ NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *path = [array objectAtIndex:0]; NSString *full_path = [path stringByAppendingPathComponent:@”file.plist”]; return full_path; }
进行储存之前我们需要知道储存的路径,iOS中使用NSSearchPathForDirectoriesInDomains方法能够获得当前应用的路径。
NSDocumentDirectory参数意味着我们想要把搜索Documents文件夹的路径(一般数据都会存储在Documents里),NSUserDomainMask参数意味着搜索范围在当前沙盒内,stringByAppendingPathComponent为添加file.plist到路径的最后。
//储存信息到plist - (IBAction)saveInfo:(id)sender { NSMutableArray *array = [[NSMutableArray alloc]init]; [array addObject:_nameField.text]; [array addObject:_stuNumField.text]; [array writeToFile:[self filePath] atomically:YES];//写入plist [array release]; }
建立数组之后,添加数据,调用writeToFile:atomically 方法就能写入plist了。
//从plist中读取数据 - (IBAction)loadInfo:(id)sender { NSString *filePath = [self filePath]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ //文件存在 NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath]; _nameField.text = [array objectAtIndex:0]; _stuNumField.text = [array objectAtIndex:1]; [array release]; } else{ NSLog(@"文件不存在,读取失败"); } }
[NSFileManagerdefaultManager]fileExistsAtPath:filePath]为判断文件是否存在,不存在则不进行读取操作。
//清除数据 - (IBAction)clearInfo:(id)sender { [_nameField setText:nil]; [_stuNumField setText:nil]; } @end
atany原创,转载请注明博主与博文链接,未经博主允许,禁止任何商业用途。
博文地址:http://blog.csdn.net/yang8456211/article/details/11783823
博客地址:http://blog.csdn.net/yang8456211
—— by atany