归档数据,然后将其加载到 viewdidload
Posted
技术标签:
【中文标题】归档数据,然后将其加载到 viewdidload【英文标题】:Archiving data and then loading it on viewdidload 【发布时间】:2014-03-20 16:05:51 【问题描述】:我正在学习 Objective-C 教程,在这项任务中,我必须制作一个地址簿样式的应用程序,在按下按钮后存储联系人详细信息,然后在下一次加载时恢复它们。
无法弄清楚为什么文本似乎没有被保存 - 所以下次我在模拟器中加载应用程序时显然不会加载。
[super viewDidLoad];
NSFileManager *filemgr;
NSString *documentsDirectory;
NSArray *directoryPaths;
filemgr =[NSFileManager defaultManager];
directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
documentsDirectory =[directoryPaths objectAtIndex:0];
filePath =[[NSString alloc]initWithString:[documentsDirectory stringByAppendingPathComponent:@"userInfo.dat"]];
if ([filemgr fileExistsAtPath:filePath])
NSMutableArray *userData;
userData =[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
txtFirstName.text =[userData objectAtIndex:0];
txtLastName.text =[userData objectAtIndex:1];
txtEmail.text =[userData objectAtIndex:2];
txtPhone.text =[userData objectAtIndex:3];
NSLog(@"File Has Been loaded");
else
NSLog(@"Error.");
- (IBAction)btnSaveDetails:(id)sender
NSMutableArray *contactDetails;
contactDetails =[[NSMutableArray alloc]init];
[contactDetails addObject:txtFirstName.text];
[contactDetails addObject:txtLastName.text];
[contactDetails addObject:txtEmail.text];
[contactDetails addObject:txtPhone.text];
[NSKeyedArchiver archiveRootObject:contactDetails toFile:filePath];
NSLog(@"File Saved");
提前致谢
【问题讨论】:
您实际上并没有将 keyedarchiver 返回的 NSData 写入文件 【参考方案1】:你试过了吗?
-(id)viewDidLoad
NSMutableArray * userData = [[NSMutableArray alloc] init];
NSData * downloadedData = [[NSData alloc] initWithContentsOfFile: [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"]];
if (downloadedData.length)
[userData setArray:[NSKeyedUnarchiver unarchiveObjectWithData:downloadedData]];
NSLog(@"userData :%@", userData);
downloadedData = nil;
-(IBAction)btnSaveDetails:(id)sender
NSMutableArray * contactDetails =[[NSMutableArray alloc]init];
[contactDetails addObject:txtFirstName.text];
[contactDetails addObject:txtLastName.text];
[contactDetails addObject:txtEmail.text];
[contactDetails addObject:txtPhone.text];
NSData * contactData = [NSKeyedArchiver archivedDataWithRootObject:contactDetails];
[contactData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"] atomically:YES];
contactData = nil;
【讨论】:
谢谢@Natarajan 我使用了你的代码,但仍然没有保存/加载 设置你的文件路径 = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"];或 filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"] 让它工作@Natarajan 谢谢。只需要弄清楚它是如何工作的!不完全理解 filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/userInfo.plist"];或:[contactData writeToFile:filePath atomically:YES];联系人数据 = 无;以上是关于归档数据,然后将其加载到 viewdidload的主要内容,如果未能解决你的问题,请参考以下文章
将 json 文档归档到 Azure Blob 存储的最佳做法是啥?