iphone开发中的数据存储:Property lists

定义两个方法:

- (NSString *)dataFilePath;获取返回数据文件的完整路径名

- (void)applicationWillResignActive:(NSNotification *)notification;保存数据,参数notification的作用是在对象之间传递通知,保持通信。

#define kFilename        @"data.plist"


- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}

 

- (void)applicationWillResignActive:(NSNotification *)notification {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:field1.text];
[array addObject:field2.text];
[array addObject:field3.text];
[array addObject:field4.text];
[array writeToFile:[self dataFilePath] atomically:YES];
}

(例子程序为保存四个textField的字符)

之后在viewDidLoad中添加代码:

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
field1.text = [array objectAtIndex:0];
field2.text = [array objectAtIndex:1];
field3.text = [array objectAtIndex:2];
field4.text = [array objectAtIndex:3];
}

UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:app];
}




posted on 2012-03-27 09:26  老Zhan  阅读(338)  评论(0编辑  收藏  举报