Fork me on GitHub

plist中数据存取

NSArray 对象保存

NSString *strOne = @"Persistent data1";
NSString *strTwo = @"Persistent data 2";
 
NSMutableArray *persistentArray = [[NSMutableArray alloc] init];
[persistentArray addObject:strOne];
[persistentArray addObject:strTwo];
 
 NSArray *filePathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
 NSString *filePath =
[[filePathArray objectAtIndex:0] stringByAppendingPathComponent:@"mydatas.plist"];

 [[NSArray arrayWithObjects:persistentArray,nil] writeToFile:filePath atomically:NO];
 
 //load
 NSMutableArray *saveDataArray = [[NSMutableArray alloc] init];
 if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
  saveDataArray = [NSMutableArray arrayWithContentsOfFile:filePath];  
 else
  saveDataArray = [NSMutableArray arrayWithContentsOfFile:[[NSBundle   
mainBundle]pathForResource:@"Savedatas" ofType:@"plist"]];        

 NSArray *strArray = [saveDataArray objectAtIndex:0];
 NSString *UnstrOne = [strArray objectAtIndex:0];
 NSString *UnstrTwo = [strArray objectAtIndex:1];

nsstring对象保存NSData*dataToWrite =[[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];

NSString*docsDirectory=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];

NSString*path =[docsDirectory stringByAppendingPathComponent:@"fileName.txt"];

// Write the file

[dataToWrite writeToFile:path encoding:NSUTF8StringEncodingerror:nil];


// Read the file
NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncodingerror:nil];
// Check if file exists
NSFileManager*fileManager =[NSFileManager defaultManager];
[fileManager fileExistsAtPath:path];
// Returns a BOOL    
// Remove the file
[fileManager removeItemAtPath:path error:NULL];
// Cleanup
[stringFromFile release];
[fileManager release];

posted on 2012-02-09 12:16  pengyingh  阅读(223)  评论(0)    收藏  举报

导航