读书人

plist资料操作

发布时间: 2012-07-16 15:44:59 作者: rapoo

plist文件操作

?

?

//入

- (void)writePlist :(NSString *)name :(NSString *)password

{

? ? //取得案路

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

? ? NSString *documentsDirectory = [paths objectAtIndex:0];

? ? //documentsDirectory路,可健入以下程式以示其路

? ? //NSLog(@"%@", documentsDirectory);

?

? ? //在Finder中示隐藏文件

? ? //打端入

? ? //defaults write com.apple.finder AppleShowAllFiles -bool true

? ? //KillAll Finder

? ? //相反

? ? //defaults write com.apple.finder AppleShowAllFiles -bool false

? ? //KillAll Finder

?

? ? //plist命名

? ? NSString *filePath = [documentsDirectory stringByAppendingString:@"/data.plist"];

? ? NSFileManager *fileManager = [NSFileManager defaultManager];

? ? NSMutableDictionary *plistDict;

?

? ? //查案是否存在,return false建

? ? if ([fileManager fileExistsAtPath: filePath])

? ? {

? ? ? ? plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

? ? }else{

? ? ? ? plistDict = [[NSMutableDictionary alloc] init];

? ? }

?

? ? //先查看是否已有obj在plist

? ? if ([plistDict objectForKey:name])

? ? {

? ? ? ? newUserLabel.text = [NSString stringWithFormat:@"%@ is already in list", name];

? ? }

? ? else

? ? {

? ? ? ? //向字典追加

? ? ? ? [plistDict setObject:password forKey:name];

? ? ? ? //把追加之入file

? ? ? ? if ([plistDict writeToFile:filePath atomically: YES]) {

? ? ? ? ? ? newUserLabel.text = [NSString stringWithFormat:@"User %@ create success!", name];

? ? ? ? ? ? NSLog(@"writePlist success");

? ? ? ? } else {

? ? ? ? ? ? NSLog(@"writePlist fail");

? ? ? ? }

? ? }

? ? //放

? ? [plistDict release];

}

?

//取

- (void)readPlist :(NSString *)name :(NSString *)password

{

? ? NSString *checkPassword;

?

? ? //取得案路

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

? ? NSString *documentsDirectory = [paths objectAtIndex:0];

? ? NSString *filePath = [documentsDirectory stringByAppendingString:@"/data.plist"];

? ? NSFileManager *fileManager = [NSFileManager defaultManager];

? ? NSMutableDictionary *plistDict;

? ? //查案是否存在

? ? if ([fileManager fileExistsAtPath: filePath])

? ? {

? ? ? ? NSLog(@"File here.");

? ? ? ? //存在的把plist中的料取出入字典plistDict

? ? ? ? plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];

? ? }else{

? ? ? ? NSLog(@"File not here.");

? ? ? ? plistDict = [[NSMutableDictionary alloc] init];

? ? }

?

? ? //使用objectForKey以字取得其value

? ? checkPassword = [plistDict objectForKey:name];

?

? ? //使用isEqualToString比入

? ? if ([checkPassword isEqualToString:password])

? ? {

? ? ? ? loginLabel.text = [NSString stringWithFormat:@"%@ login ok!", name];

? ? }

? ? else

? ? {

? ? ? ? loginLabel.text = [NSString stringWithFormat:@"登入名或密!"];?

? ? }

? ? [plistDict release];

}

读书人网 >移动开发

热点推荐