功能創建一個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];
}
------------------------------------------------------------------------------------------------------------------------------------------------------------
參考代碼:
plist 文件讀寫
//1. 創建一個plist文件
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); www.2cto.com
NSString *path=[paths objectAtIndex:0];
NSLog(@"path = %@",path);
NSString *filename=[path stringByAppendingPathComponent:@"test.plist"];
NSFileManager* fm = [NSFileManager defaultManager];
[fm createFileAtPath:filename contents:nil attributes:nil];
//NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
//創建一個dic,寫到plist文件裡
NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:@"sina",@"1",@"163",@"2",nil];
[dic writeToFile:filename atomically:YES];
//讀文件
NSDictionary* dic2 = [NSDictionary dictionaryWithContentsOfFile:filename];
NSLog(@"dic is:%@",dic2);