将数据从 plist 加载到另一个类
Posted
技术标签:
【中文标题】将数据从 plist 加载到另一个类【英文标题】:loading data from plist to another class 【发布时间】:2012-12-17 16:53:09 【问题描述】:在我的应用中,plist 文件被保存到文档目录中,每个文件名都是当前日期+时间。
我正在将文档目录中的文件列表加载到表中:filesTableVC.m.
每次我想将所选文件加载到新类时:oldFormVC.m
但是这个类是空开的。
我不确定问题出在哪里。
filesTableVC.m:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
oldFormVC *oldForm = [[oldFormVC alloc] initWithNibName:nil bundle:nil];
//load previous data:
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:[fileList objectAtIndex:indexPath.row]];
// check to see if Data.plist exists in documents
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath])
// if not in documents, get property list from main bundle
plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
// read property list into memory as an NSData object
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSString *errorDesc = nil;
NSPropertyListFormat format;
// convert static property liost into dictionary object
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp)
NSLog(@"Error reading plist: %@, format: %d", errorDesc, format);
// assign values
self.theDate = [temp objectForKey:@"theDate"];
self.theTime = [temp objectForKey:@"theTime"];
self.carNumber = [temp objectForKey:@"carNumber"];
self.driverName = [temp objectForKey:@"driverName"];
[self presentViewController:oldForm animated:YES completion:nil];
oldFormVC.m:
- (void)viewDidLoad
[super viewDidLoad];
dateField.text = theDate;
timeField.text = theTime;
carNumberField.text = carNumber;
driverNameField.text = driverName;
【问题讨论】:
你使用 self.carNumber 我假设你的意思是 oldForm.carNumber 【参考方案1】:在viewDidAppear
写你的代码
- (void)viewDidAppear:(BOOL)animated
dateField.text = theDate;
timeField.text = theTime;
carNumberField.text = carNumber;
driverNameField.text = driverName;
另外,在 filesTableVC.m 中更改此代码:
oldForm.dateField = [temp objectForKey:@"theDate"];
oldForm.theTime = [temp objectForKey:@"theTime"];
oldForm.carNumber = [temp objectForKey:@"carNumber"];
oldForm.driverName = [temp objectForKey:@"driverName"];
希望对你有帮助
【讨论】:
@Arkins 接受答案,因为它可以帮助其他人参考以上是关于将数据从 plist 加载到另一个类的主要内容,如果未能解决你的问题,请参考以下文章
NSMutableArray 从 plist 返回 Null