很早以前写了一个库,结果找不到了。再害怕遗忘,随便整理了几点操作,以后想起来再补充。
//.h
#import <Foundation/Foundation.h>
@interface BPlistFileManager : NSObject {
@private NSMutableString* filename_;
@private NSString *path;
}
+(BPlistFileManager*)getInstance;
-(void)setPlistName:(NSString*)filename withPath:(NSString*)filepath;
-(void)setPlistName:(NSString*)filefullname;
-(void)createPlistWithArray:(NSMutableArray*)array;
-(void)createPlistWithDictionary:(NSMutableDictionary*)dictionary;
-(NSArray*)readPlistwithArray;
-(NSDictionary*)readPlistwithDictionary;
@end
//.m
static BPlistFileManager* instance;
@implementation BPlistFileManager
-(id)init
{
self = [super init];
if (self) {
}
return self;
}
+(BPlistFileManager*)getInstance
{
if (instance==nil) {
instance = [[BPlistFileManager alloc] init];
}
return instance;
}
-(void)setPlistName:(NSString*)filename withPath:(NSString*)filepath
{
if(filepath==nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
path = [paths objectAtIndex:0];
}
else
{
path =[filepath retain];
}
if(filename!= nil)
{
filename_ = [NSMutableString stringWithString:filename];
}
filename_ = [NSMutableString stringWithString:[path stringByAppendingPathComponent:filename_]];
}
-(void)setPlistName:(NSString*)filefullname
{
if(filefullname!= nil)
{
filename_ = [NSMutableString stringWithString:filefullname];
}
}
-(void)createPlistWithArray:(NSMutableArray*)array
{
if (array!=nil)
[array writeToFile:filename_ atomically:YES];
}
-(void)createPlistWithDictionary:(NSMutableDictionary*)dictionary
{
if(dictionary != nil)
[dictionary writeToFile:filename_ atomically:YES];
}
-(NSArray*)readPlistwithArray
{
NSArray *array = [NSArray arrayWithContentsOfFile:filename_];
// [[NSArray alloc] initWithContentsOfFile:filename_];
return [array autorelease];
}
-(NSDictionary*)readPlistwithDictionary
{
NSDictionary* dic = [NSDictionary dictionaryWithContentsOfFile:filename_];
return [dic autorelease];
}
@end
//main.m中的操作
BPlistFileManager *obj = [BPlistFileManager getInstance];
//create file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString* path = [paths objectAtIndex:0];
NSString* filename =@"test.plist";
[obj setPlistName:filename withPath:path];
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"test1",@"test2", nil];
[obj createPlistWithArray:array];
//read file
NSArray *arrayobj = [obj readPlistwithArray];
for(id obj in arrayobj)
{
NSLog(@"obj:%@",obj);
}
//read existed file.
NSBundle *thisBundle = [NSBundle mainBundle];
NSString* commonDictionaryPath = [thisBundle pathForResource:@"dic" ofType:@"plist"];
if(commonDictionaryPath != nil)
{
[obj setPlistName:commonDictionaryPath];
NSDictionary *dic = [obj readPlistwithDictionary];
NSDictionary *subdic=[dic objectForKey:@"dic"];
NSString* name =[subdic objectForKey:@"name"];
NSLog(@"name:%@",name);
NSString* address =[subdic objectForKey:@"address"];
NSLog(@"address:%@",address);
}