2011年4月24日 星期日

操作plist檔案

新增plist file



// AboutMeViewController.h
#import
@interface AboutMeViewController : UIViewController {
IBOutlet UITextField *uName;
IBOutlet UITextField *uJob;
IBOutlet UILabel *errorCode;
IBOutlet UILabel *msg;
}
@property (nonatomic, retain) IBOutlet UITextField *uName;
@property (nonatomic, retain) IBOutlet UITextField *uJob;
@property (nonatomic, retain) IBOutlet UILabel *errorCode;
@property (nonatomic, retain) IBOutlet UILabel *msg;
-(IBAction)getInfo:(id)sender;
-(IBAction)writeInfo:(id)sender;
@end
// AboutMeViewController.m
#import "AboutMeViewController.h"
@implementation AboutMeViewController
@synthesize uName, uJob, errorCode,msg;
-(IBAction)getInfo:(id)sender
{
NSString *error = nil;
NSPropertyListFormat format;
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"member" ofType:@"plist"];
NSData *plist = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSDictionary *tempData = (NSDictionary *)
[NSPropertyListSerialization propertyListFromData:plist
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&error];
self.uName.text = [tempData objectForKey:@"username"];
self.uJob.text = [tempData objectForKey:@"job"];
}
-(IBAction)writeInfo:(id)sender
{
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"member" ofType:@"plist"];
NSData *plist = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
[plistDict setValue:@"工人" forKey:@"job"];
[plistDict writeToFile:plistPath atomically:YES];
self.msg.text = @"已寫入資料";
}

沒有留言:

張貼留言